【问题标题】:React testing library's waitFor() returns nullReact 测试库 waitFor() 返回 null
【发布时间】:2020-07-19 23:18:07
【问题描述】:

我正在测试我的登录表单的提交事件是否被拒绝。如果用户只是提交了表单而没有填写用户名和密码,则必须显示两条错误消息并且它应该通过测试。但测试结果却相反:显示用户名和密码错误信息为null。我尝试使用setTimeout(),因为onSubmit 事件由于axios 是异步的,但它仍然没有通过测试。我将waitFor() 实用程序用于异步提交事件的方式有什么问题吗?

it('Should render username and password error messages when both inputs are blank', () => {
    const { getByTestId, queryByTestId } = render(<Index />)

    fireEvent.submit(getByTestId('form'))

    expect(getByTestId('submit-button').disabled).toBeTruthy()

    setTimeout(async () => {
        expect(getByTestId('submit-button').disabled).toBeFalsy()

        const usernameError = await waitFor(() => queryByTestId('username-error'))
        expect(usernameError).toBeInTheDocument()

        const passwordError = await waitFor(() => queryByTestId('password-error'))
        expect(passwordError).toBeInTheDocument()
    }, 0)
})

【问题讨论】:

  • 这可能意味着该元素不存在。尝试打印 dom 以确保

标签: reactjs unit-testing jestjs react-testing-library


【解决方案1】:

对测试进行了一些更改,可能会解决此问题。请在下面的代码中找到它们作为 cmets

// The first is adding async to the callback of your `it` so you don't have to use a timeout
it('Should render username and password error messages when both inputs are blank', async () => {
    const { getByTestId, findByTestId, queryByTestId } = render(<Index />)

    expect(getByTestId('submit-button').disabled).toBeTruthy()

    fireEvent.submit(getByTestId('form'))

    // Here we can use waitFor which waits until the promise triggered by the last fireEvent finishes.
    await waitFor(() => {
        expect(getByTestId('submit-button').disabled).toBeFalsy()
    })

    // Finally, you should be able to just use getByTestId to locate the elements you need, and given that the promises are resolved, they should be in the document
    expect(getByTestId('username-error')).toBeInTheDocument()
    expect(getByTestId('password-error')).toBeInTheDocument()
})

如果这些建议不起作用,请同时复制正在测试的组件的代码

【讨论】:

  • 这并不能真正回答问题,因为您刚刚删除了waitFor。你还应该解释你改变了什么以及为什么。
  • findByTestId 返回一个空对象。使用queryByTestId,它将返回null。另外,为什么要删除waitFor()
  • 对不起,我刚刚更新了所有希望使用getByTestId。所以问题是,你真的不需要使用那些waitFor。您首先拥有它们的原因是因为您在提交表单后等待某些承诺得到解决。这现在被await act(async ... 取代。如果这不起作用,请同时添加 HTML 的代码,以便更容易找到问题。
  • @Victor 非常感谢您的回答!我想知道您是否可以指出任何有关正确使用 await act(..... 或从 waitFor() 切换的文档?谢谢!
  • 你好@Sturzl。肯定的事。请阅读 react 测试库作者kentcdodds.com/blog/… 的这篇文章。另外,官方文档也不错testing-library.com/docs/dom-testing-library/api-async#waitfor
猜你喜欢
  • 2021-06-14
  • 2021-07-17
  • 2021-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-30
  • 1970-01-01
  • 2020-11-05
相关资源
最近更新 更多