let state = 'Monday';
export function greet() {
return 'hello ' + state;
}
↑ 凭借良好的编码实践,您不会遇到这样的非纯函数,但由于某些特殊原因我遇到了。
然后,开个 Jest :
import { greet } from './functions';
test('a', () => {
expect(greet()).toBe('hello Monday');
});
test('b', () => {
let state = 'Tuesday';
expect(greet()).toBe('hello Tuesday'); // fail! Still 'hello Monday'
});
在这种情况下,我如何模拟状态?
最佳答案
您可以使用rewire将模块作用域中定义的私有(private)变量替换为模拟变量。
The current version of rewire is only compatible with CommonJS modules. see limitations
因此下面的示例将 ES 模块更改为 CommonJS 模块。
例如
functions.js
:
let state = 'Monday';
function greet() {
return 'hello ' + state;
}
exports.greet = greet;
functions.test.js
:
const rewire = require('rewire');
const functions = rewire('./functions');
describe('60763037', () => {
test('a', () => {
expect(functions.greet()).toBe('hello Monday');
});
test('b', () => {
functions.__set__('state', 'Tuesday');
expect(functions.greet()).toBe('hello Tuesday');
});
});
单元测试结果:
PASS stackoverflow/60763037/functions.test.js
60763037
✓ a (3ms)
✓ b (1ms)
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 5.04s
关于javascript - 我可以模拟/监视非纯函数的父作用域中存在的变量值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60763037/