Course contentsShow
← React
Lesson 2152 of 2,39647. Testing Patterns and Best PracticesFree lesson

waitForElementToBeRemoved for Disappearing Elements

Use waitForElementToBeRemoved when asserting that loading spinners or modals are removed from the DOM after async operations.

waitForElementToBeRemoved for Disappearing Elements

You'll learn how to properly test that temporary UI elements like loading spinners and modals actually disappear after async operations complete.

The Problem with Testing Disappearance

When testing async components, you often need to verify that elements leave the DOM—not just that new content arrives. For example, a loading spinner should vanish when data loads, or a modal should close when an action completes. Using waitFor with a queryBy works, but there's a clearer, more semantic approach.

What waitForElementToBeRemoved Does

The waitForElementToBeRemoved utility specifically waits for an element that's currently in the DOM to be removed. It throws an error if the element isn't present when you call it (meaning it was never there to begin with), which catches test setup mistakes early.

import { render, screen, waitForElementToBeRemoved } from '@testing-library/react';

test('loading spinner disappears after data loads', async () => {
  render(<UserProfile userId="123" />);
  
  const spinner = screen.getByText(/loading/i);
  
  // Wait for the spinner to be removed from the DOM
  await waitForElementToBeRemoved(spinner);
  
  // Now assert the actual content is visible
  expect(screen.getByText(/john doe/i)).toBeInTheDocument();
});

Why Not Just Use waitFor?

You could write await waitFor(() => expect(screen.queryByText(/loading/i)).not.toBeInTheDocument()), but waitForElementToBeRemoved is more explicit about your intent, more readable, and catches the edge case where the element was never there at all.

The Key Constraint

You must query the element before calling waitForElementToBeRemoved—you're passing the element reference itself, not a query function. This ensures it exists initially, making your test more robust.

Key Takeaway: Use waitForElementToBeRemoved when testing that temporary UI elements like spinners or modals disappear—it's semantically clearer than waitFor and validates the element existed in the first place.