简体   繁体   English

Jest 无法在异步函数上调用 spy,但在浏览器控制台中调用了函数

[英]Jest fails to call spy on async function, but function is called in browser console

I've written a jest test to cover an onBlur event being called.我写了一个玩笑测试来覆盖被调用的 onBlur 事件。 Im using react-testing-library and material-ui.我正在使用 react-testing-library 和 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, 'test@gmail.com')
  expect(spy).not.toHaveBeenCalled()
  fireEvent.blur(fld)
  expect(spy).toHaveBeenCalledTimes(1)
  expect(spy).toHaveBeenCalledWith('test@gmail.com')  
})

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.我试图设置一个代码沙盒,但不幸的是,这失败了,关于将测试包装在act块中的错误。 This does not occur in my local environment.这不会发生在我的本地环境中。

How do I get this test to complete successfully?我如何才能成功完成此测试?

您应该await调用该方法:

await waitFor(() => expect(spy).toHaveBeenCalledTimes(1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM