1+ import { describe , it , expect , vi , beforeEach } from 'vitest'
2+ import { useValidation } from '@/composables/useValidation'
3+ import { ref , nextTick } from 'vue'
4+
5+ const createBaseField = ( overrides = { } ) => ( {
6+ name : 'testField' ,
7+ model : 'test' ,
8+ type : 'text' ,
9+ validate : 'onBlur' ,
10+ ...overrides
11+ } )
12+
13+ const model = {
14+ test : ''
15+ }
16+ const emits = vi . fn ( )
17+
18+ describe ( 'useValidation' , ( ) => {
19+
20+ beforeEach ( ( ) => {
21+ vi . clearAllMocks ( )
22+ } )
23+
24+ it ( 'should initialize with empty errors' , ( ) => {
25+ const field = createBaseField ( )
26+ const value = ref ( '' )
27+
28+ const { errors } = useValidation (
29+ model ,
30+ field ,
31+ value ,
32+ { } ,
33+ emits ,
34+ false ,
35+ false ,
36+ false
37+ )
38+
39+ expect ( errors . value ) . toEqual ( [ ] )
40+ } )
41+
42+ it ( 'Should validate on blur when validate is set to onBlur' , async ( ) => {
43+ const field = createBaseField ( {
44+ validate : 'onBlur' ,
45+ validator : [ ( value ) => value . length > 0 ]
46+ } )
47+ const value = ref ( '' )
48+
49+ const { onBlur } = useValidation (
50+ model ,
51+ field ,
52+ value ,
53+ { } ,
54+ emits ,
55+ false ,
56+ true ,
57+ false
58+ )
59+
60+ await onBlur ( )
61+
62+ expect ( emits ) . toHaveBeenCalled ( )
63+ } )
64+
65+ it ( 'Should validate on change when validate is set to onChanged' , async ( ) => {
66+ const field = createBaseField ( {
67+ validate : 'onChanged' ,
68+ validator : [ ( value ) => value . length > 0 ]
69+ } )
70+ const value = ref ( '' )
71+
72+ const { onChanged } = useValidation (
73+ model ,
74+ field ,
75+ value ,
76+ { } ,
77+ emits ,
78+ false ,
79+ true ,
80+ false
81+ )
82+
83+ await onChanged ( )
84+
85+ expect ( emits ) . toHaveBeenCalled ( )
86+ } )
87+
88+ it ( 'Should handle multiple validators' , async ( ) => {
89+ const field = createBaseField ( {
90+ validator : [
91+ ( value ) => value . length >= 3 ,
92+ ( value ) => value . length <= 10
93+ ]
94+ } )
95+ const value = ref ( 'a' )
96+
97+ const { onBlur, errors } = useValidation (
98+ model ,
99+ field ,
100+ value ,
101+ { } ,
102+ emits ,
103+ false ,
104+ true ,
105+ false
106+ )
107+
108+ await onBlur ( )
109+ await nextTick ( )
110+
111+ expect ( errors . value ) . toContain ( 'Field is invalid' )
112+ } )
113+
114+ it ( 'Should clear errors when validation passes' , async ( ) => {
115+ const field = createBaseField ( {
116+ validator : [ ( value ) => value . length > 0 ]
117+ } )
118+ const value = ref ( '' )
119+
120+ const { onBlur, errors } = useValidation (
121+ model ,
122+ field ,
123+ value ,
124+ { } ,
125+ emits ,
126+ false ,
127+ true ,
128+ false
129+ )
130+
131+ await onBlur ( )
132+ expect ( errors . value . length ) . toBeGreaterThan ( 0 )
133+
134+ value . value = 'valid value'
135+ await onBlur ( )
136+ expect ( errors . value ) . toEqual ( [ ] )
137+ } )
138+ } )
0 commit comments