Reputation: 408
I've written a jest test to cover an onBlur event being called. Im using react-testing-library and material-ui.
Here is the test code:
test('fires onBlur handler', async () => {
const spy = jest.fn()
const { getByPlaceholderText } = render(
<FormEmailAsync placeholder={'Your Email'} onBlurred={data => spy(data)} />
)
const fld = getByPlaceholderText('Your Email')
expect(fld)
userEvent.type(fld, '[email protected]')
expect(spy).not.toHaveBeenCalled()
fireEvent.blur(fld)
expect(spy).toHaveBeenCalledTimes(1)
expect(spy).toHaveBeenCalledWith('[email protected]')
})
And the code I am trying to assert on
const [theState, asyncFunc] = useAsyncFn(async value => {
const returnedSchema = await schema.validate(value)
return returnedSchema
}, [])
const onBlurFunc = async (name, event) => {
let returnFromAsync = await asyncFunc(event)
console.log(returnFromAsync)
onBlurred(returnFromAsync)
}
I've attempted to setup a codesandbox but unfortunately this is failing with an error about wrapping the tests in an act
block. This does not occur in my local environment.
How do I get this test to complete successfully?
Upvotes: 1
Views: 2274
Reputation: 26988
You should await
for the method to be called:
await waitFor(() => expect(spy).toHaveBeenCalledTimes(1))
Upvotes: 3