当我尝试以下代码时
script.js
var aMyVar = [];
[...]
async function load(bHard){
console.log(aMyVar);
[...]
}
[...]
module.exports = {
load
}
script.test.js
const {
load
} = require('../script.js');
[...]
describe('My Block', function () {
test('My Test', async () => {
global.aMyVar = [{"Key":"Test"}];
await load(true);
[...]
});
});
[...]
预期的行为:console.log打印“ [{“ Key”:“ Test”}]“”
观察到的行为:console.log显示“ []”
怎么了?
答案 0 :(得分:1)
您可以使用rewire包来修改在模块作用域中声明的变量。
例如
script.js
:
var aMyVar = [];
async function load(bHard) {
console.log(aMyVar);
}
module.exports = { load };
script.test.js
:
const rewire = require('rewire');
const mod = rewire('./script');
describe('My Block', function() {
test('My Test', async () => {
mod.__set__('aMyVar', [{ Key: 'Test' }]);
await mod.load(true);
});
});
单元测试结果:
PASS src/stackoverflow/63676669/script.test.js
My Block
✓ My Test (7ms)
[ { Key: 'Test' } ]
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.842s, estimated 10s