如何在玩笑测试中共享设置和拆卸? [英] 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.
我想在需要但无法找到方法的测试文件之间共享该安装拆卸代码,并且我不想在每个组件测试中都重复beforeEach和afterEach.
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
但是似乎beforeEach并未运行.
But it seems that beforeEach is not being run.
推荐答案
react_helpers
出现问题.如果未使用导入,则不会评估ES模块,因此,如果以下未引用container
,则import container from './react_helpers.js'
将是空操作.而且ES模块仅在首次导入时进行评估,因此它们可能不适合此任务.
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.
如果需要共享数据,则需要在commonSetup
和评估它的上下文之间共享一个公共对象,例如
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;
}
然后可以在需要此设置的测试中导入commonSetup
并对其进行评估:
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;
...
});
这篇关于如何在玩笑测试中共享设置和拆卸?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!