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

300
Views
Global beforeEach and afterEach Jest in React

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!

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

0

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.

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!