[英]@testing-library/react (rtl) 'waitFor' makes only success without await keyword
await waitFor()
makes my test fail but waitFor()
makes my test successful (without await). await waitFor()
使我的测试失败,但waitFor()
使我的测试成功(没有等待)。
The official doc said官方文档说
The async methods return a Promise, so you must always use await or.then(done) when calling them.
异步方法返回 Promise,因此在调用它们时必须始终使用 await 或.then(done)。 ( https://testing-library.com/docs/guide-disappearance )
( https://testing-library.com/docs/guide-disappearance )
I don't know how can I test correctly.我不知道如何正确测试。 do I have to use
rerender
?我必须使用重新
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 });
});
});
If I use watingFor()
with out await
it was not failed but also not successful.如果我在没有
await
的情况下使用watingFor()
,它并没有失败,但也没有成功。
expect statement pass through without testing.期望语句通过而无需测试。
waitFor()
without await is my misconception.没有等待的
waitFor()
是我的误解。 It's always successful even if has to fail.即使失败了也总是成功的。
Finally, I have known that test framework can not detect results of changing props.最后,我知道测试框架无法检测到更改道具的结果。 The props are passed from Parent Component even if it is in redux store in fact.
道具是从父组件传递的,即使它实际上在 redux 存储中。
In summary, I want to test Child Component.总之,我想测试子组件。 It gets props from Parent Component, Parent gets data to pass props from redux store.
它从 Parent Component 获取 props,Parent 获取数据以从 redux store 传递 props。
Click event of Child fires dispatch and change store state well. Child fires dispatch 的 Click 事件并更改存储 state 好。 But in test runner, because rendering is isolated, It was seemed to cause an error.
但是在测试运行器中,由于渲染是孤立的,似乎会导致错误。 Store state was changed but props was passed still not changed So I changed Child data structure not getting props from Parent but getting from store.
存储 state 已更改,但通过的道具仍未更改所以我更改了子数据结构,不是从父级获取道具,而是从存储区获取。
because if you are not awaiting, you are getting a promise, which is a truthy value.因为如果您不等待,您将得到一个 promise,这是一个真实值。 now if you do await and the promise resolves to a falsy value only in that case your test case will fail
现在,如果您等待并且 promise 仅在这种情况下解析为虚假值,您的测试用例将失败
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.