我使用Jest编写一些测试用例。我需要测试的JavaScript文件有一些全局变量,我想获取并设置这些全局变量的值。我试图导出全局变量并直接使用in test.js。但是,它不起作用。有一个简单的代码:
simple.js:
var someGlobalVariable = '';
//Basic Function with no return type
function firstFunction() {
someGlobalVariable = 'hello';
}
//Function which returns String
function secondFunction() {
//firstFunction();
console.log(someGlobalVariable);
return someGlobalVariable;
}
module.exports.firstFunction= firstFunction;
module.exports.secondFunction = secondFunction;
module.exports.someGlobalVariable = someGlobalVariable;
simple.test.js:const jstester = require('./Test');
test('secondFunction', ()=>{
//jstester.firstFunction();
jstester.someGlobalVariable = 'world';
console.log(jstester.someGlobalVariable);
expect(jstester.secondFunction()).toMatch('world');
});
结果是:
FAIL ./Test.test.js
✕ secondFunction (19ms)
● secondFunction
expect(received).toMatch(expected)
Expected value to match:
"world"
Received:
""
5 | jstester.someGlobalVariable = 'world';
6 | console.log(jstester.someGlobalVariable);
> 7 | expect(jstester.secondFunction()).toMatch('world');
| ^
8 | });
9 |
10 |
at Object.toMatch (Test.test.js:7:39)
console.log Test.test.js:6
world
console.log Test.js:12
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 0.961s, estimated 1s
Ran all test suites.
simple.js中的someGlobalVariable仍然是“。但我希望simple.test.js将值更改为”world“。
有没有办法直接改变价值?或者我必须在simple.js中添加set和get函数?
我不确定你的用例,但我确实有一些建议:
someGlobalVariable
更改为对象并直接进行变异。解决方案将是这样的:simple.js:
var someGlobalVariable = {
value: "hello"
};
//Basic Function with no return type
function firstFunction() {
someGlobalVariable.value = "hello";
}
//Function which returns String
function secondFunction() {
//firstFunction();
console.log(someGlobalVariable.value);
return someGlobalVariable.value;
}
module.exports.firstFunction = firstFunction;
module.exports.secondFunction = secondFunction;
module.exports.someGlobalVariable = someGlobalVariable;
simple.test.js:
const jstester = require("./simple");
test("secondFunction", () => {
//jstester.firstFunction();
jstester.someGlobalVariable.value = "world";
console.log(jstester.someGlobalVariable.value);
expect(jstester.secondFunction()).toMatch("world");
});
这是有效的,因为您没有更改对主题的引用,您只是在基础引用相同时更改属性。
secondFunction
收到一个变量,原始的someGlobalVariable
作为默认值:
function secondFunction(dependency = someGlobalVariable){// firstFunction();的console.log(someGlobalVariable); return someGlobalVariable; }这样,您可以将任意值传递给secondFunction
并测试您的特定情况。但是,这不会改变simple.js
中的全局变量。
希望这个帮手!干杯:)