【发布时间】:2021-04-19 19:52:10
【问题描述】:
我目前正在尝试使用 React 测试库和 Jest 测试一个 React 应用程序。这是我的代码的 sn-p:
const renderComponent = async () => {
component = render(
<Component
... props
></Component>
).container
return waitFor(() =>
expect(
component.querySelector(#some-element)
).toBeInTheDocument(),
).then(() => {
console.log("done with method")
return "good to go"
})
}
beforeEach(async () => {
return renderComponent().then(() => {
console.log("done")
return "done with before each"
})
})
test('should test work', async () => {
const element = getById(component as HTMLElement, 'element-id')
userEvent.type(element!, "hello")
// this test fails
expect(mockFunction).lastCalledWith("hello")
})
我的问题不是我的测试失败,而是测试套件的执行顺序。在我的控制台中,console.log 消息按以下顺序打印出来:
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 4.123 s
Watch Usage: Press w to show more.
console.log
done with method
console.log
done with before each
为什么在 beforeEach 中的逻辑完成之前测试失败了?任何帮助,将不胜感激!谢谢:)
【问题讨论】:
-
我不知道到底是什么问题,但由于传递给
beforeEach的异步方法,它似乎可能会出现故障。 -
你认为方法不应该是异步的吗?我只是尝试删除 async 关键字,不幸的是,它没有做任何事情。测试应该在
beforeEach方法中的承诺解决后运行,如 Jest 文档中所述:“在此文件中的每个测试运行之前运行一个函数。如果函数返回一个承诺,Jest 等待该承诺解决在运行测试之前。” -
尽量将您的断言放在
test块中,而不是beforeEach中。在这种情况下,直接在您的测试中调用await renderComponent()。
标签: reactjs jestjs react-testing-library