sajad torkamani

Wait for elements to appear

Using findBy query

test('movie title appears', async () => {
  // element is initially not present...
  // wait for appearance and return the element
  const movie = await findByText('the lion king')
})

Using waitFor

test('movie title appears', async () => {
  // element is initially not present...

  // wait for appearance inside an assertion
  await waitFor(() => {
    expect(getByText('the lion king')).toBeInTheDocument()
  })
})

Wait for disappearance

Using waitForElementToBeRemoved

This will use a MutationObserver by using a callback to query for the element on each DOM mutation and resolve to true when the element is removed. This is more efficient than polling using waitFor.

test('movie title no longer present in DOM', async () => {
  // element is removed
  await waitForElementToBeRemoved(() => queryByText('the mummy'))
})

Using waitFor

Keep polling at regular intervals until the callback doesn’t throw an error.

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 itself
  await waitFor(() => {
    expect(queryByText('i, robot')).not.toBeInTheDocument()
  })
})

Sources