Skip to content

Commit a50cab7

Browse files
committed
Added hook test
1 parent 2a2b0d5 commit a50cab7

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

src/useFieldArray.test.js

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import React from 'react'
2+
import { render, cleanup } from 'react-testing-library'
3+
import 'jest-dom/extend-expect'
4+
import arrayMutators from 'final-form-arrays'
5+
import { ErrorBoundary } from './testUtils'
6+
import { Form } from 'react-final-form'
7+
import useFieldArray from './useFieldArray'
8+
9+
const onSubmitMock = values => {}
10+
11+
describe('FieldArray', () => {
12+
afterEach(cleanup)
13+
14+
// Most of the functionality of useFieldArray is tested in FieldArray.test.js
15+
// This file is only for testing its use as a hook in other components
16+
17+
it('should warn if not used inside a form', () => {
18+
jest.spyOn(console, 'error').mockImplementation(() => {})
19+
const errorSpy = jest.fn()
20+
const MyFieldComponent = () => {
21+
useFieldArray('name')
22+
return <div />
23+
}
24+
render(
25+
<ErrorBoundary spy={errorSpy}>
26+
<MyFieldComponent />
27+
</ErrorBoundary>
28+
)
29+
expect(errorSpy).toHaveBeenCalled()
30+
expect(errorSpy).toHaveBeenCalledTimes(1)
31+
expect(errorSpy.mock.calls[0][0].message).toBe(
32+
'useFieldArray must be used inside of a <Form> component'
33+
)
34+
console.error.mockRestore()
35+
})
36+
37+
it('should track field array state', () => {
38+
const spy = jest.fn()
39+
const MyFieldArray = () => {
40+
spy(useFieldArray('names'))
41+
return null
42+
}
43+
render(
44+
<Form onSubmit={onSubmitMock} mutators={arrayMutators} subscription={{}}>
45+
{() => (
46+
<form>
47+
<MyFieldArray />
48+
</form>
49+
)}
50+
</Form>
51+
)
52+
expect(spy).toHaveBeenCalled()
53+
expect(spy).toHaveBeenCalledTimes(1)
54+
expect(spy.mock.calls[0][0].fields.length).toBe(0)
55+
56+
spy.mock.calls[0][0].fields.push('bob')
57+
58+
expect(spy).toHaveBeenCalledTimes(2)
59+
expect(spy.mock.calls[1][0].fields.length).toBe(1)
60+
})
61+
})

0 commit comments

Comments
 (0)