|
| 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