id | title |
---|---|
guide-disappearance | Appearance and Disappearance |
Sometimes you need to test that an element is present and then disappears or vice versa.
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.
test('movie title appears',async()=>{// element is initially not present...// wait for appearance and return the elementconstmovie=awaitfindByText('the lion king')})
test('movie title appears',async()=>{// element is initially not present...// wait for appearance inside an assertionawaitwaitFor(()=>{expect(getByText('the lion king')).toBeInTheDocument()})})
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.
test('movie title no longer present in DOM',async()=>{// element is removedawaitwaitForElementToBeRemoved(()=>queryByText('the mummy'))})
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.
test('movie title goes away',async()=>{// element is initially present...// note use of queryBy instead of getBy to return null// instead of throwing in the query itselfawaitwaitFor(()=>{expect(queryByText('i, robot')).not.toBeInTheDocument()})})
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:
constsubmitButton=screen.queryByText('submit')expect(submitButton).toBeNull()// it doesn't exist
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.
constsubmitButtons=screen.queryAllByText('submit')expect(submitButtons).toHaveLength(0)// expect no elements
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
.
import'@testing-library/jest-dom'// use `queryBy` to avoid throwing an error with `getBy`constsubmitButton=screen.queryByText('submit')expect(submitButton).not.toBeInTheDocument()