我无法获得使用 sinon 测试代码的基础知识。我有一个简单的模块,它调用两个内部函数并检查它们的结果。我打算使用存根来改变这些函数的输出,以测试模块如何响应。这可能吗?
脚本.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;
})
})
})