@testing库/反应 (RTL) 'waitFor' 只有成功而没有等待关键字



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()而不使用await它不会失败,但也不是真正的成功。

期望语句在不进行测试的情况下通过。waitFor()不等待是我的误解。即使不得不失败,它也总是成功的。

最后,我知道测试框架无法检测到道具变化的结果。道具是从父组件传递的,即使它实际上在redux存储中。

总之,我想测试子组件。它从Parent组件中获取道具,Parent从redux存储中获取数据来传递道具。

点击Child fires调度事件,并很好地更改存储状态。但在测试运行程序中,由于渲染是孤立的,它似乎导致了一个错误。商店状态已更改,但道具已传递但仍未更改所以我改变了Child的数据结构,不是从Parent获得道具,而是从商店获得。

因为如果你不等待,你就会得到一个承诺,这是一个真实的价值。现在,如果您确实在等待,并且promise只在这种情况下解析为一个错误值,那么您的测试用例将无法通过

最新更新