Appearance and Disappearance
Sometimes you need to test that an element is present and then disappears or vice versa.
Waiting for appearance
If you need to wait for an element to appear, the async wait
utilities allow you to wait for an assertion to be satisfied before
proceeding. The wait utilities retry until the query passes or times out. The
async methods return a Promise, so you must always use await
or .then(done)
when calling them.
findBy
Queries
1. Using waitFor
2. Using Waiting for disappearance
The waitForElementToBeRemoved
async helper function uses a
callback to query for the element on each DOM mutation and resolves to true
when the element is removed.
Using
MutationObserver
is more efficient than polling the DOM at regular intervals with waitFor
.
The waitFor
async helper function retries until the wrapped
function stops throwing an error. This can be used to assert that an element
disappears from the page.
Asserting elements are not present
The standard getBy
methods throw an error when they can't find an element, so
if you want to make an assertion that an element is not present in the DOM,
you can use queryBy
APIs instead:
The queryAll
APIs version return an array of matching nodes. The length of the
array can be useful for assertions after elements are added or removed from the
DOM.
not.toBeInTheDocument
The jest-dom
utility library provides the
.toBeInTheDocument()
matcher, which can be used to assert that an element is
in the body of the document, or not. This can be more meaningful than asserting
a query result is null
.