按照问题enter link description here的建议,我模拟了readFileSync并模拟了我的外部函数,现在我想验证变量值是否设置为预期值
file.js
const fs1 = require('fs');
let param;
module.export = {
test,
param
}
function test (outputParam) {
param = fs1.readFileSync(outputParam);
}
我已将这个readFileSync存入存根,并且它返回指定的文件内容,如下面的测试所示
当我运行测试时,我想查看变量param是否具有文件内容值
test.spec.js
let expect = require('chai').expect;
let fs = require("fs");
let sinon = require("sinon");
let filejs = require('./file.js');
it('should run only the outer function and test if variable param is set to `this is my file content` ' ,function() {
let someArg ="file.xml";
sinon.stub(fs,'readFileSync').callsFake ((someArg) => {
return "this is my file content";
});
var mock = sinon.mock(filejs);
mock.expects('test').withArgs(someArg);
expect(filejs.param).to.equal('this is my file content');
})
从file.js,您可以看到属性param从“ readFileSync”获取值,该值被存根以返回值
当我运行测试
Expect(filejs.param).to.equal('这是我的文件内容');
AssertionError:预期未定义等于“这是我的文件内容”
最佳答案
请注意module.exports
的正确拼写-不是module.export
。
在您的file.js中,变量param
未初始化,因此它将获得值undefined
,并且也将使用该值导出。如果以后修改param
,则导出的值不会更改。导出仅将属性绑定到值,而不绑定到变量。实际上,您甚至不需要局部变量。要至少在Node中动态更改导出的值,只需在module.exports
上重新分配属性。
const fs1 = require('fs');
module.exports = {
test
}
function test (outputParam) {
module.exports.param = fs1.readFileSync(outputParam);
}
至于您的test.spec.js,您已经非常接近要开始工作了。对不应该在集线器下调用的方法进行存根之后,只需调用您的
test
函数,并传递实参即可。那里不需要模拟。let expect = require('chai').expect;
let fs = require("fs");
let sinon = require("sinon");
let filejs = require('./file.js');
it('should run only the outer function and test if variable param is set to `this is my file content` ' ,function() {
let someArg ="file.xml";
sinon.stub(fs,'readFileSync').callsFake ((someArg) => {
return "this is my file content";
});
filejs.test(someArg);
expect(filejs.param).to.equal('this is my file content');
});