-
-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathuseFieldArray.test.tsx
More file actions
245 lines (219 loc) · 6.37 KB
/
useFieldArray.test.tsx
File metadata and controls
245 lines (219 loc) · 6.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import * as React from 'react'
import { act, render, cleanup, waitFor } from '@testing-library/react'
import '@testing-library/jest-dom'
import arrayMutators from 'final-form-arrays'
import { ErrorBoundary } from './testUtils'
import { Form, useField, useFormState } from 'react-final-form'
import useFieldArray from './useFieldArray'
import { ARRAY_ERROR } from 'final-form'
const onSubmitMock = (values: any) => {}
describe('FieldArray', () => {
afterEach(cleanup)
// Most of the functionality of useFieldArray is tested in FieldArray.test.js
// This file is only for testing its use as a hook in other components
it('should warn if not used inside a form', () => {
jest.spyOn(console, 'error').mockImplementation(() => {})
const errorSpy = jest.fn()
const MyFieldComponent = () => {
useFieldArray('name')
return <div />
}
render(
<ErrorBoundary spy={errorSpy}>
<MyFieldComponent />
</ErrorBoundary>
)
expect(errorSpy).toHaveBeenCalled()
expect(errorSpy).toHaveBeenCalledTimes(1)
expect(errorSpy.mock.calls[0][0].message).toBe(
'useFieldArray must be used inside of a <Form> component'
)
;(console.error as any).mockRestore()
})
it('should track field array state', () => {
const spy = jest.fn()
const MyFieldArray = () => {
spy(useFieldArray('names'))
return null
}
render(
<Form
onSubmit={onSubmitMock}
mutators={arrayMutators as any}
subscription={{}}
>
{() => (
<form>
<MyFieldArray />
</form>
)}
</Form>
)
expect(spy).toHaveBeenCalled()
expect(spy).toHaveBeenCalledTimes(2) // React 18+ renders twice in dev
expect(spy.mock.calls[0][0].fields.length).toBe(0)
act(() => spy.mock.calls[0][0].fields.push('bob'))
expect(spy).toHaveBeenCalledTimes(3) // 2 initial + 1 after push
expect(spy.mock.calls[2][0].fields.length).toBe(1)
expect(spy.mock.calls[2][0].fields.value).toEqual(['bob'])
})
it('should not call validator when no validate prop is provided', () => {
// This test verifies the fix: when no validator is provided,
// undefined is passed instead of a no-op function that always returns undefined.
// This prevents final-form from tracking this field as having a validator,
// which would trigger unnecessary form-wide validation.
const useFieldSpy = jest.spyOn(require('react-final-form'), 'useField')
const MyFieldArray = () => {
const fieldArray = useFieldArray('names')
return null
}
render(
<Form
onSubmit={onSubmitMock}
mutators={arrayMutators as any}
subscription={{}}
>
{() => (
<form>
<MyFieldArray />
</form>
)}
</Form>
)
// Verify that useField was called with validate: undefined
const useFieldCalls = useFieldSpy.mock.calls
const relevantCall = useFieldCalls.find((call) => call[0] === 'names')
expect(relevantCall).toBeDefined()
expect(relevantCall![1].validate).toBeUndefined()
useFieldSpy.mockRestore()
})
it('should call validator when validate prop is provided', () => {
const fieldValidate = jest.fn(() => undefined)
const fieldArraySpy = jest.fn()
const MyFieldArray = () => {
const fieldArray = useFieldArray('names', { validate: fieldValidate })
fieldArraySpy(fieldArray)
return null
}
render(
<Form
onSubmit={onSubmitMock}
mutators={arrayMutators as any}
subscription={{}}
>
{() => (
<form>
<MyFieldArray />
</form>
)}
</Form>
)
// Field validation should be called on initial render
expect(fieldValidate).toHaveBeenCalled()
const initialCalls = fieldValidate.mock.calls.length
// Get the last call before mutations
const lastCallBeforeMutations = fieldArraySpy.mock.calls.length - 1
// Push an item to trigger validation again
act(() =>
fieldArraySpy.mock.calls[lastCallBeforeMutations][0].fields.push('alice')
)
// Field validation should be called again after mutation
expect(fieldValidate.mock.calls.length).toBeGreaterThan(initialCalls)
})
it('should handle array errors', () => {
const spy = jest.fn()
const MyFieldArray = () => {
spy(useFieldArray('names', { validate: (values) => ['required'] }))
return null
}
render(
<Form
onSubmit={onSubmitMock}
mutators={arrayMutators as any}
subscription={{}}
>
{() => (
<form>
<MyFieldArray />
</form>
)}
</Form>
)
expect(spy).toHaveBeenCalledWith(
expect.objectContaining({
meta: expect.objectContaining({
error: ['required']
})
})
)
})
it('should handle string error', () => {
const spy = jest.fn()
const spyState = jest.fn()
const MyFieldArray = () => {
spy(useFieldArray('names', { validate: (values) => 'failed' }))
return null
}
const Debug = () => {
spyState(useFormState().errors)
return null
}
render(
<Form
onSubmit={onSubmitMock}
mutators={arrayMutators as any}
subscription={{}}
>
{() => (
<form>
<MyFieldArray />
<Debug />
</form>
)}
</Form>
)
expect(spy).toHaveBeenCalledWith(
expect.objectContaining({
meta: expect.objectContaining({
error: 'failed'
})
})
)
const expected: any[] = []
;(expected as any)[ARRAY_ERROR] = 'failed'
expect(spyState).toHaveBeenCalledWith({ names: expected })
})
it('should handle Promises errors', async () => {
const spy = jest.fn()
const MyFieldArray = () => {
spy(
useFieldArray('names', {
validate: (values) => Promise.resolve(['await fail'])
})
)
return null
}
render(
<Form
onSubmit={onSubmitMock}
mutators={arrayMutators as any}
subscription={{}}
>
{() => (
<form>
<MyFieldArray />
</form>
)}
</Form>
)
waitFor(() =>
expect(spy).toHaveBeenCalledWith(
expect.objectContaining({
meta: expect.objectContaining({
error: ['await fail']
})
})
)
)
})
})