Cleanup Between Tests
You'll learn: Why RTL automatically cleans up after each test and why you rarely need to worry about test isolation.
The Automatic Cleanup Guarantee
React Testing Library automatically cleans up after every test. When you use the render function, RTL tracks the DOM nodes it creates and removes them after the test completes—no manual intervention required. This happens through an automatic afterEach hook that RTL registers globally when you import it.
Think of it like a restaurant kitchen: after each dish is prepared (test runs), the workspace is automatically wiped clean before the next order begins. You don't have to manually scrub the counters—the system does it for you.
Why This Matters
Without cleanup, DOM nodes from previous tests would accumulate in the jsdom environment, potentially causing:
- False test results from leftover elements interfering with queries
- Memory leaks as unmounted components pile up
- Flaky tests where execution order affects outcomes
RTL's automatic cleanup ensures each test starts with a fresh DOM slate, giving you true test isolation.
When You Don't Need to Worry
If you're using modern @testing-library/react (version 9+), cleanup is built-in. You don't need to:
- Import
cleanupmanually - Call it in
afterEachhooks - Think about it at all
The magic happens behind the scenes when you use render.
The Rare Exception
The only time you might care is if you're not using render but manipulating the DOM directly (very uncommon in RTL). In those edge cases, you'd handle cleanup yourself—but if you're following RTL's philosophy, you won't encounter this.
Key Takeaway: RTL's automatic cleanup between tests means you can focus on writing tests, not managing test infrastructure—each test runs in complete isolation by default.