React Testing Library cleanup not working in Jest's describe bocks

To understand this we need to understand a little bit about how Jest runs our tests and how React Testing Library renders our components.


Jest

Consider the code below and try to guess what the output will be:

describe('First describe', () => {
  console.log('First describe');

  it('First test', () => {
    console.log('First test');
  });
});

describe('Second describe', () => {
  console.log('Second describe');

  it('Second test', () => {
    console.log('Second test');
  });
});

Output (hover to see):

First describe
Second describe
First test
Second test

Note that all describe methods were initialised before the tests started to run.

This should already give you an idea of the problem, but let's now look at RTL.


React Testing Library

Consider the code below and try to guess what the DOM will look like in the console:

const Greeting = () => 'Hello world';

describe('First describe', () => {
  const wrapper = render(<Greeting />);

  it('First test', () => {
    console.log(wrapper.debug());
  });
});

describe('Second describe', () => {
  render(<Greeting />);
});

Output (hover to see):

<body> <div>Hello world</div> <div>Hello world</div> </body>

When we don't specify a base element to the render function, it always uses the same document.body

The <div> elements wrapping Hello world are added by RTL when we don't specify a custom container.

All RTL queries are bound to the base element by default--document.body in this case.

Therefore,

getByText('Hello world'); // will find two elements and throw


This is how the code in RTL looks like for the render function. (semi-pseudo code)

if(!baseElement) {
  baseElement = document.body // body will be shared across renders
}
if(!container) {
  baseElement.appendChild(document.createElement('div')) // wraps our component
}
ReactDOM.render(component, container)

return {  container, baseElement, ...getQueriesForElement(baseElement)  }


To solve this issue

Do one of the following:

  1. call render inside the it or test methods
  2. specify the container in the queries
  3. specify a diferent base element for each render

I was running into a separate problem, but in the midst found the likely answer to your problem.

Jest describe blocks run in sequence before any of the tests run. Source

So you should basically never execute code in a describe block aside from variable scoping. If you need to set a variable or render a mock that is used across multiple tests, put it in a lifecycle method like beforeAll or beforeEach.