Jasmine: Use `throwUnless` for testing-library's `waitFor`

Posted . Visible to the public.

testing-library Show archive.org snapshot are widely used testing utilities libraries for javascript dependent frontend testing. The main utilities provided are query methods, user interactions, dom expectations and interacting with components of several frontend frameworks, which allows us to worry less about the details happening in the browser and focus more on user centric tests instead!


Some of the time you will find a necessity to use methods like waitFor Show archive.org snapshot , because your code itself may trigger something asynchronous (e.g. animations or setTimeout). Let's see what the docs state on this method:

When in need to wait for any period of time you can use waitFor, to wait for your expectations to pass. Returning a falsy condition is not sufficient to trigger a retry, the callback must throw an error in order to retry the condition.

Let's say we have an animation for a smoothly appearing tooltip once the user hovers an info icon. Our test assertions might look like this:

await user.hover(infoIcon)
await waitFor(() => expect(await findByText('Some tooltip text').toBeVisible()) 

But wait! Our test is failing flaky, what is happening? Shouldn't waitFor wait until the element has actually been found? Sadly no! Jasmine's assertions with their expect method do not throw errors and just continue with the test instead!

Happy enough they provide another solution! throwUnless Show archive.org snapshot and throwUnlessAsync Show archive.org snapshot create an expectation that will throw a ThrowUnlessFailure Show archive.org snapshot error if the expectation fails:

await waitFor(() => throwUnlessAsync(await findByText('Some tooltip text').toBeVisible()) 
Felix Eschey
Last edit
Felix Eschey
Keywords
retries
License
Source code in this card is licensed under the MIT License.
Posted by Felix Eschey to makandra dev (2024-09-24 06:11)