field-form
field-form copied to clipboard
form.validateFields return error with `outOfDate:=true` in test
The code works perfectly fine in the apps.
However, when I tested it using Jest, it will always return error upon calling form.validateFields().
The sample error returned is
{
values: { value: 'Updated' },
errorFields: [],
outOfDate: true
}
I try to look at the source code and it said outOfDate means change when validating.
Does anybody knows how to avoid this error?
Here is my sample test codes
test('should be able to update the values', async () => {
renderComponent()
const valueElem = await screen.findByText('value 1')
userEvent.click(valueElem)
const valueInput = await screen.findByTestId('editable-cell-input')
userEvent.clear(valueInput)
userEvent.type(valueInput, 'abc {enter}', { allAtOnce: false })
await waitFor(() => {
expect(screen.queryByTestId('editable-cell-input')).toBeNull()
expect(screen.getByText('value 1 Updated')).toBeDefined()
expect(updateInventoryValue).toHaveBeenCalledWith(1, {
value: 'value 1 Updated',
})
})
})
In apps
const save = async () => {
try {
const params = await form.validateFields()
toggleEdit()
handleSave(record.id, params)
} catch (errInfo) {
console.log(errInfo)
notification.error({
message: 'Something went wrong!',
description: 'Please try again.',
})
}
}
<Form form={form}>
<Form.Item
style={{
margin: 0,
}}
name={title}
>
<Input
ref={inputRef}
onPressEnter={save}
onBlur={save}
data-testid="editable-cell-input"
/>
</Form.Item>
</Form>
Have you found a solution ?
For those reading this thread later, a possible workaround is to use a setTimeout around the form.validateFields(). For some reason, it will validate without the outOfDate error. As a helper method, you can use something like:
const formValidateFields = (form: FormInstance): Promise<any> => {
return new Promise((resolve, reject) => {
setTimeout(() => {
form
.validateFields()
.then((values) => resolve(values))
.catch((e) => reject(e))
})
})
}