I'm using react, so before each test I need to create a container element. Currently, I have something like this:
import { screen } from '@testing-library/react';
import { render, unmountComponentAtNode } from 'react-dom';
import Form from './Form';
let container: Element | null = null;
// setup a DOM element as a render target
beforeEach(() => {
container = document.createElement('div');
document.body.appendChild(container);
});
// cleanup on exiting
afterEach(() => {
unmountComponentAtNode(container!);
container?.remove();
container = null;
})
test('renders with a heading', () => {
render(
<Form heading={'Form Heading'} />, container
);
const element = screen.getByText(/form heading/i);
expect(element).toBeInTheDocument();
});
As you probably expected, I need to do the beforeEach and afterEach setup for each test file. Can this be made global(after being global, we still need access the to container variable)? Looking forward to your reply!
While this isn't technically the answer to the question you asked, this is the solution to the underlying problem you have.
You are importing the wrong render:
import { render, unmountComponentAtNode } from 'react-dom';
The render function imported from react-dom is used to actually render the result to the browser, not for testing.
You need to: import {render} from '@testing-library/react'. The testing library does all that container management for you.
If you actually need the container for anything, you can still do:
const {container} = render(/* ... */);
But most of the time that is not necessary.