[英]@testing-library/react (rtl) 'waitFor' makes only success without await keyword
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 });
});
});
如果我在没有await
的情况下使用watingFor()
,它并没有失败,但也没有成功。
期望语句通过而无需测试。 没有等待的waitFor()
是我的误解。 即使失败了也总是成功的。
最后,我知道测试框架无法检测到更改道具的结果。 道具是从父组件传递的,即使它实际上在 redux 存储中。
总之,我想测试子组件。 它从 Parent Component 获取 props,Parent 获取数据以从 redux store 传递 props。
Child fires dispatch 的 Click 事件并更改存储 state 好。 但是在测试运行器中,由于渲染是孤立的,似乎会导致错误。 存储 state 已更改,但通过的道具仍未更改所以我更改了子数据结构,不是从父级获取道具,而是从存储区获取。
因为如果您不等待,您将得到一个 promise,这是一个真实值。 现在,如果您等待并且 promise 仅在这种情况下解析为虚假值,您的测试用例将失败
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.