Skip to content

Commit dcb4c8b

Browse files
committed
Write test for FormContext's onChange behavior
1 parent 315ac5b commit dcb4c8b

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const mockSchema = {
2+
$id: 'https://example.com/mock.schema.json',
3+
$schema: 'http://json-schema.org/draft-07/schema#',
4+
title: 'Mock',
5+
type: 'object',
6+
properties: {
7+
firstField: {
8+
type: 'string',
9+
description: 'The first field.',
10+
title: 'First field',
11+
},
12+
secondField: {
13+
type: 'string',
14+
description: 'The second field.',
15+
title: 'Second field',
16+
},
17+
thirdField: {
18+
type: 'string',
19+
description: 'The third field.',
20+
title: 'Third field',
21+
},
22+
},
23+
}
24+
25+
export default mockSchema
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import { fireEvent, render } from '@vtex/test-tools/react'
2+
import React from 'react'
3+
import { Controller } from 'react-hook-form'
4+
5+
import { useObject } from '../../hooks/useObject'
6+
import mockSchema from '../__mocks__/mockSchema'
7+
import { FormContext } from '../FormContext'
8+
9+
const ObjectRenderer = (props: { pointer: string }) => {
10+
const fields = useObject({ pointer: props.pointer })
11+
12+
return (
13+
<>
14+
{fields.map(field => {
15+
const fieldJsonSchema = field.getObject()
16+
17+
return (
18+
<Controller
19+
as={<input aria-label={fieldJsonSchema.title} name={field.name} />}
20+
control={field.formContext.control}
21+
defaultValue=""
22+
key={field.pointer}
23+
name={field.pointer}
24+
/>
25+
)
26+
})}
27+
</>
28+
)
29+
}
30+
31+
test('should call onChange when something changes', () => {
32+
const changeHandlerMock = jest.fn()
33+
34+
const { getByLabelText } = render(
35+
<FormContext onChange={changeHandlerMock} schema={mockSchema}>
36+
<ObjectRenderer pointer="#" />
37+
</FormContext>
38+
)
39+
40+
expect(changeHandlerMock).toHaveBeenCalledTimes(0)
41+
42+
let changeValue
43+
44+
Object.entries(mockSchema.properties).forEach(
45+
([fieldName, fieldProperties], index) => {
46+
const fieldNumber = index + 1
47+
48+
const inputElement = getByLabelText(fieldProperties.title)
49+
50+
const fieldNewValue = `new value for field ${fieldNumber}`
51+
52+
fireEvent.change(inputElement, {
53+
target: { value: fieldNewValue },
54+
})
55+
56+
expect(changeHandlerMock).toHaveBeenCalledTimes(fieldNumber)
57+
58+
changeValue = { ...changeValue, [fieldName]: fieldNewValue }
59+
60+
expect(changeHandlerMock).toHaveBeenLastCalledWith(changeValue)
61+
}
62+
)
63+
})

0 commit comments

Comments
 (0)