React Testing Library – using ‘await wait()’ after fireEvent

5 months later I’m coming back to answer my question (I’ve learned a lot since posting this question lol)….

First of all, since it is 5 months later I want to underscore that it is better to use the userEvent library instead of fireEvent if possible.

I also would be remiss to not call out that there are a lot of antipatterns in the code …You should only ever make one assertion in waitFor. You should avoid using getByTestId in favor of more accessible alternatives.

And finally the reason the first test was failing is that you can not use wait with getBy*. getBy is not async and will not wait. This would have been the better solution:

fireEvent.click(button);
const nameWrapper =  await findByTestId('name_wrapper');

Then the test would have waited on the nameWrapper element to be available.

The second test passed because getBy is wrapped in RTL’s async utility, wait (wait is now deprecated in favor of waitFor). That is essentially what findBy does under the hood — findBy is the async version of getBy.

When I posted the question I didn’t fully understand that await is a Javascript key word (and just syntactical sugar to make code wait on a promise to resolve). wait (now waitFor) is a utility from RTL that will make execution of the test wait until the callback does not throw an error.

Leave a Comment

tech