当测试两个相互独立地修改同一状态变量myVar
的函数时,我希望能够隔离似乎相关的副作用。
example.js
export function foobar() {
sideEffect1();
sideEffect2();
}
let myVar;
function sideEffect1() {
if (myVar === undefined) {
myVar = 'foo';
}
}
function sideEffect2() {
if (myVar === undefined) {
myVar = 'bar';
}
}
example.test.js
import example, {return2} from "../src/example";
test('Test Side Effect 1', () => {
let se = example.__get__('sideEffect1');
se();
let myVar = example.__get__('myVar');
expect(myVar).toBe("foo");
});
test('Test Side Effect 2', () => {
let se = example.__get__('sideEffect2');
se();
let myVar = example.__get__('myVar');
expect(myVar).toBe("bar");
});
输出
> jest "js/tests/example.test.js"
FAIL js/tests/example.test.js (6.056 s)
✓ Test Side Effect 1 (1 ms)
✕ Test Side Effect 2 (4 ms)
● Test Side Effect 2
expect(received).toBe(expected) // Object.is equality
Expected: "bar"
Received: "foo"
23 | se();
24 | let myVar = example.__get__('myVar');
> 25 | expect(myVar).toBe("bar");
| ^
26 | });
27 |
28 |
如果我分别运行每个测试,两者都可以正常工作。问题似乎是在运行整个测试套件时。这是对我在更复杂的应用程序中使用的代码中遇到的相同问题的简化。有什么想法可以解决它的原因和方法吗?
babel.config.json
{
"presets": ["@babel/preset-env"],
"plugins": ["babel-plugin-rewire"]
}
模块在执行开始时加载,并作为一个模块加载-因此您的example.js可以正确执行,无论是先执行sideEffect1
还是sideEffect2
的函数,该函数设置变量myVar
,然后获得该变量值