我希望能够隔离在测试两个myVar
相互独立地修改相同状态变量的函数时似乎相关的副作用。
例子.js
export function foobar() {
sideEffect1();
sideEffect2();
}
let myVar;
function sideEffect1() {
if (myVar === undefined) {
myVar = 'foo';
}
}
function sideEffect2() {
if (myVar === undefined) {
myVar = 'bar';
}
}
例子.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"]
}