eloyesp
eloyesp

Reputation: 3285

How do I share setup and teardown in jest tests?

I've found react tests recipes quite verbose, because they need to setup a container and cleanup that after each test.

I would like to share that setup-teardown code between test files that require that but could not find a way to do it and I would prefer not to repeat beforeEach and afterEach on every component test.

I've tried with something like:

# sample.test.js

#...
import container from './react_helpers.js'
#...

# react_helpers.js

import { unmountComponentAtNode } from "react-dom"

let container = null;

beforeEach(() => {
  // setup a DOM element as a render target
  container = document.createElement("div");
  document.body.appendChild(container);
});

afterEach(() => {
  // cleanup on exiting
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

export default container

But it seems that beforeEach is not being run.

Upvotes: 2

Views: 1059

Answers (1)

Estus Flask
Estus Flask

Reputation: 222603

There are problems with react_helpers. ES modules aren't evaluated if imports aren't in use so import container from './react_helpers.js' will be a no-op if container isn't referenced below. And ES modules are evaluated only on first import, so they may be not suitable for this task.

In case there's a need to share data, a common objects need to be shared between commonSetup and the context where it's evaluated, like explained here:

export default function commonSetup(context = {}) {
  beforeEach(() => {
    context.container = ...;
    ...
  });
  afterEach(...);

  return context;
}

Then commonSetup can be imported and evaluated in tests that need this setup:

import commonSetup from './react_helpers.js'

...

let context = commonSetup();

it('...', () => {
  let { container } = context;
  ...
});

Upvotes: 1

Related Questions