How do I share setup and teardown in jest tests?

你。 提交于 2021-01-28 04:31:58

问题


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.


回答1:


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;
  ...
});


来源:https://stackoverflow.com/questions/62582096/how-do-i-share-setup-and-teardown-in-jest-tests

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!