@testing-library/react (rtl) 'waitFor' 只在没有 await 关键字的情况下成功
@testing-library/react (rtl) 'waitFor' makes only success without await keyword
await waitFor()
使我的测试失败,但 waitFor()
使我的测试成功(无需等待)。
官方文档说
The async methods return a Promise, so you must always use await or .then(done) when calling them. (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()
没有 await 是我的误解。即使不得不失败,它也总是成功的。
终于知道了,测试框架是检测不到props变化的结果的。
道具是从父组件传递的,即使它实际上在 redux store 中。
综上所述,我想测试子组件。
它从父组件获取道具,父组件从 redux store 获取数据以传递道具。
Child 的点击事件会触发调度并很好地更改存储状态。
但是在test runner中,因为渲染是隔离的,所以好像会报错。
商店状态已更改但道具已通过但仍未更改
所以我更改了 Child 数据结构,不是从 Parent 获取道具而是从商店获取。
因为如果你没有等待,你就会得到一个承诺,这是一个真实的价值。
现在,如果您确实等待并且承诺仅在这种情况下解析为虚假值,您的测试用例将失败
await waitFor()
使我的测试失败,但 waitFor()
使我的测试成功(无需等待)。
官方文档说
The async methods return a Promise, so you must always use await or .then(done) when calling them. (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()
没有 await 是我的误解。即使不得不失败,它也总是成功的。
终于知道了,测试框架是检测不到props变化的结果的。 道具是从父组件传递的,即使它实际上在 redux store 中。
综上所述,我想测试子组件。 它从父组件获取道具,父组件从 redux store 获取数据以传递道具。
Child 的点击事件会触发调度并很好地更改存储状态。 但是在test runner中,因为渲染是隔离的,所以好像会报错。 商店状态已更改但道具已通过但仍未更改 所以我更改了 Child 数据结构,不是从 Parent 获取道具而是从商店获取。
因为如果你没有等待,你就会得到一个承诺,这是一个真实的价值。 现在,如果您确实等待并且承诺仅在这种情况下解析为虚假值,您的测试用例将失败