我无法掌握使用 sinon 测试代码的基础知识。我有一个简单的模块,它调用两个内部函数并检查它们的结果。我将使用 stub 来改变这些函数的输出,以测试模块的响应方式。这可能吗?
脚本.js
let check1 = function(){return true}
let check2 = function(){return true}
let startFunc = function(){console.log('checks Passed')}
let sendLog = function(message){console.log(message)}
module.exports.check=function(){
console.log('check1: ', check1())
console.log('check2: ', check2())
if (!check1() || !check2()) {
startFunc()
sendLog("started")
}
}
测试.js:
"use strict";
var chai = require("chai");
var sinon = require("sinon");
var sinonChai = require("sinon-chai");
var expect = chai.expect;
chai.use(sinonChai);
var scripts = require('./scripts')
describe("scripts", () => {
describe("check", () => {
it("should startFunc and send Log if check1 || check2 is false", () => {
var check1 = sinon.stub(check1);
check1.yields(false);
var check2 = sinon.stub(check2);
check2.yields(true);
var startFunc = sinon.stub(startFunc);
var sendLog = sinon.stub(sendLog);
scripts.check();
expect(sendLog).to.have.been.calledWith("started")
expect(startFunc).to.have.been.calledOnce;
})
})
})
编辑:
我已经通过使该函数可访问来设法使测试正常工作。我仍然不确定这是最好的方法
脚本.js
let check1 = function(){return true}
let check2 = function(){return true}
let startFunc = function(){console.log('checks Passed')}
let sendLog = function(message){console.log(message)}
module.exports.check1 = check1
module.exports.check2 = check2
module.exports.startFunc = startFunc
module.exports.sendLog = sendLog
module.exports.check=function(){
console.log('check1: ', this.check1())
console.log('check2: ', this.check2())
if (!this.check1() || !this.check2()) {
this.startFunc()
this.sendLog("started")
}
}
测试.js:
"use strict";
var chai = require("chai");
var sinon = require("sinon");
var sinonChai = require("sinon-chai");
var expect = chai.expect;
chai.use(sinonChai);
var scripts = require('./scripts')
describe("scripts", () => {
describe("check", () => {
it("should startFunc and send Log if check1 || check2 is false", () => {
var check1 = sinon.stub(scripts,'check1',() => {return true});
var check2 = sinon.stub(scripts,'check2',()=> {return false});
var startFunc = sinon.stub(scripts,'startFunc');
var sendLog = sinon.stub(scripts,'sendLog');
scripts.check();
expect(sendLog).to.have.been.calledWith("started")
expect(startFunc).to.have.been.calledOnce;
})
})
})
最佳答案
我只是公开模块的内部函数(就像您在上面的编辑中所做的那样)。但是,我会使用一些特殊的符号,例如_check1
和 _check2
,或代码组织,例如module.exports.privateFunctions = { check1: check1, ... };
,表示这些是内部函数,不是预期模块接口(interface)的一部分。
另一种方法(尽管我不确定这是否是一个好的做法)是通过添加内部函数作为其属性来扩展导出的方法,例如module.exports.check.check1 = check1;
。这样,每个导出的函数都会附加对其内部使用的函数的引用,这些函数的行为可以被 stub 。此外,该接口(interface)是安全的,即即使您重新定义 check.check1 = function() { return 42; };
在代码的其他部分,这不会影响 check
,因为它将调用原始的 check1
。
关于javascript - Sinon - 内部函数的基本使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42508142/