【发布时间】:2020-02-19 10:02:14
【问题描述】:
我已经存根文件的内容,所以我只能运行外部函数
file.html
<body onload ="test('file.txt')">
<body>
file.js
const fs1 = require('fs');
let param;
module.export = {
test,
test1,
param
}
function test (outputParam) {
let fileData = test1(outputParam);
param = fileData;
}
function test1(outputParam) {
let data = fs1.readFileSync(outputParam);
return data;
}
如您所见,我从 html onload 加载函数测试,然后 test1 调用并读取文件,我已将此文件内容存根,如下面的测试所示
当我运行测试时,我想查看变量 param 具有文件内容值
test.spec.js
let sinon = require("sinon");
let filejs = require('./file.js');
it('should run only the outer function' ,function() {
// I try to stub my function here
sinon.stub(filejs,'test1').callsFake ((someArg) => {
return "this is my file content";
});
// Now I will call my test function
filejs.test(someArg);
})
正如你在上面看到的,我有函数 test1,但当我运行测试时,我看到 test1 被调用并读取真实文件。
我正在使用 mocha ,我是存根或模拟概念的新手,任何建议都非常感谢。
【问题讨论】:
-
如果您不理解我的问题,请告诉我
-
sinon.stub()只能影响导出对象的属性,但test()函数直接调用内部函数test1()。sinon.stub()不能对模块的内部做任何事情。
标签: javascript unit-testing mocha.js