await waitFor()
makes my test fail but waitFor()
makes my test successful (without await).
The official doc said
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)
I don't know how can I test correctly.
do I have to use 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
forwaitFor
.The fact that then test passes if you don't useawait
is because the assertionexpect(targetItem).toHaveStyle({ color: MINT });
will not happen. Make sure you're testing the correct behaviour. – Devisor