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

我写了一个玩笑测试来覆盖被调用的 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块中的错误。这不会发生在我的本地环境中。


我如何才能成功完成此测试?


Cats萌萌
浏览 174回答 1
1回答

达令说

您应该await调用该方法:await&nbsp;waitFor(()&nbsp;=>&nbsp;expect(spy).toHaveBeenCalledTimes(1))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript