When I try with the following code
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);
[...]
});
});
[...]
Expected behaviour: console.log prints "[{"Key":"Test"}]"
Observed behaviour: console.log prints "[]"
What's wrong?
You can use rewire package to modify the variables declared in the module scope.
Eg
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);
});
});
unit test result:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.