Getting started
Before jumping into the testing part, make sure that you've configured
Jest or Vitest in your project
as specified in the documentation. Assume that render
, screen
and userEvent
variables
are imported from your project test-utils
file.
This guide is applicable to:
Testing example
In all following examples we will use AuthModal
component, it contains
a button and a modal with a simple authentication form:
Failing tests
If try to write tests for AuthModal
without any additional configuration,
you will notice that they fail because, by default, modals use Transition
component to animate opening and closing. Transition component uses setTimeout
to delay
animation start and @testing-library/react
does not wait for setTimeout
to finish.
Example of failing tests:
Fixing failing tests
The easiest way to fix this issue is to disable transitions in your tests. This can be done by creating a separate theme for tests. In this theme, you need to disable transitions for all components that you plan to test.
To create a custom theme for tests, replace your render
function
in test-utils
folder with the following code:
✅ Now the test from the previous example should pass is passing!
How to test that the modal is opened/closed?
To verify that the modal is opened, you can check that the modal heading is in the document
and an interactive element with data-autofocus
attribute has focus:
To verify that the modal has been closed, check that the modal heading is not in the document: