Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
React Testing Library waitForElementToBeRemoved not work truely

In my React application, I have a button on the screen which after clicking on it, a specific element in the screen will disappear. By Clicking the button, a state will change and after re-rendering the component, the element will disappear.

To test this scenario, I am using the React Testing library. It does not work truly by waitForElementToBeRemoved :

//element to hide
const listContainer = screen.getByRole('list'); 

//Toggle button
 const queryButton = screen.getByRole('button', {
    name: 'Query',
  })

userEvent.click(queryButton); 

//this line get error: Exceeded timeout of 20000 ms for a test.
await waitForElementToBeRemoved(() => listContainer);

but when I change waiting the process it works:

await waitFor(() => {
    expect(listContainer).not.toBeInTheDocument();
});

I don't understand why. can anyone help me?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Change your test to use:

//Toggle button
const queryButton = screen.getByRole('button', {
 name: 'Query',
})

userEvent.click(queryButton); 

// Use queryByRole instead of getByRole
await waitForElementToBeRemoved(() => screen.queryByRole('list'));

This should work as queryByRole returns null instead of an error if an item is not found. waitFor works as it retries until the wrapped function stops throwing an error (which is what getByRole does if an element is not found). If the queryByRole change still doesn't work for you, you can additionally try incrementing the timeout e.g. await waitForElementToBeRemoved(() => screen.queryByRole('list'), {timeout: 3000);

More info on the difference between waitForElementToBeRemoved and waitFor can be found here. Also check out this article which advises to only use queryBy... whenever you need to check for the non-existence of an element.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!