Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

301
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda