【发布时间】:2023-03-12 00:47:01
【问题描述】:
await waitFor() 使我的测试失败,但waitFor() 使我的测试成功(无需等待)。
官方文档说
异步方法返回一个 Promise,因此在调用它们时必须始终使用 await 或 .then(done)。 (https://testing-library.com/docs/guide-disappearance)
我不知道如何正确测试。
我必须使用rerender吗?
it('toggles active status', async () => {
render(<List {...listProps} />);
const targetItem = screen.getByRole('heading', { name: /first/i });
// de-active color is GRAY2, active color is MINT
expect(targetItem).toHaveStyle({ color: GRAY2 });
// click to change the color of targetItem
// it dispatch action that update listProps
// So changing listProps makes <List /> re-rendering
fireEvent.click(targetItem);
await waitFor(() => {
// It throws an error because the color is still GRAY2 in jest runner.
// But, in chrome browser, it's color MINT.
expect(targetItem).toHaveStyle({ color: MINT }); // fail
});
// If not use 'await' keyword, this works well.
// jest runner knows the color is MINT
waitFor(() => {
expect(targetItem).toHaveStyle({ color: MINT });
});
});
【问题讨论】:
-
我认为问题在于调度操作。使用重新渲染而不是 waitFor() 的新方法取得了成功。我猜想通过更改 props 重新渲染 DOM 的结果与组件测试无关。这样对吗?与否
-
正如文档所说,对于
waitFor,您应该始终使用await。如果您不使用await,那么测试通过的事实是因为断言expect(targetItem).toHaveStyle({ color: MINT });不会发生。确保您正在测试正确的行为。 -
@juliomalves 是的,你是对的。由于评论字符串长度的限制,我写了答案。
标签: javascript reactjs typescript react-testing-library