我写了一个开玩笑的测试来涵盖正在调用的onBlur事件。我使用 react-testing-library 和 material-ui。
以下是测试代码:
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, 'test@gmail.com')
expect(spy).not.toHaveBeenCalled()
fireEvent.blur(fld)
expect(spy).toHaveBeenCalledTimes(1)
expect(spy).toHaveBeenCalledWith('test@gmail.com')
})
以及我试图断言的代码
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)
}
我尝试设置一个代码沙箱,但不幸的是,这失败了,并且错误地将测试包装在act
块中。这在我的本地环境中不会发生。
如何成功完成此测试?
你应该await
调用的方法:
await waitFor(() => expect(spy).toHaveBeenCalledTimes(1))