sinonjs:sinon存根无法处理导出的函数



当我在为其编写mocha测试的控制器文件中require函数时,我无法截断函数functionToStub

以下是我试图实现的一个例子

file1.js—控制器文件

const functionUtil = require('./useFunc');
const newEndpoint = (req, res) => {
if(functionUtil.functionToStub()){
return "DID NOT STUB"
}
else{
return "DID STUB"
}
}

useFunc.js

var functions = {
functionToStub: functionToStub
}
function functionToStub (){
return true
}
module.exports = functions;

mocha.js

const featureUtil = require('/useFunc')
describe('When I call endpoint to stub', (done) => {
var newStub;
before(function(done) {
newStub = sinon.stub(featureUtil, 'functionToStub')
newStub.returns(false)
chai.request(app.start())
.post(`/api/testMyStub`)
.send({'test':'testBody'})
.end((err, res) => {
console.log(res.body) // Expecting DID STUB to print here but the stub doesn't work, prints DID NOT STUB
done();
});
});
after(function(done) {
newStub.restore();
done();
})
it('should send an request', (done) => {
expect(newStub).to.have.been.calledOnce
done()
}); 
});

我能够使用proxyquire实现它。我不得不稍微重写一下函数调用才能使其正常工作。我正在添加更新的测试用例:

const featureUtil = require('/useFunc')
var proxyquire =  require('proxyquire')
isLegacyPrintingEnabledStub = sinon.stub(featureUtil, 'functionToStub')
var isLegacyPrintingEnabledUtil = proxyquire('../../api/controllers/file1', {"featureUtil" : {'functionToStub': stubbedFunction }});
stubbedFunction.returns(false)
describe('When I call endpoint to stub', (done) => {
before(function(done) {
chai.request(app.start())
.post(`/api/testMyStub`)
.send({'test':'testBody'})
.end((err, res) => {
console.log(res.body) // Logs DID STUB as expected
done();
});
});
after(function(done) {
newStub.restore();
done();
})
it('should send an request', (done) => {
expect(stubbedFunction).to.have.been.calledOnce
done()
}); 
});

在这之后,我能够看到代码以预期的方式返回DID STUB

对我来说更简单的方法是:当我想用stubexport function()...时,我也有同样的问题。它不起作用。所以我将export function()转换为使用箭头函数:export const nameFunction = ()...

具有箭头功能,工作正常。

最新更新