我正在努力解决一个非常微不足道的问题。我能够在所有依赖包中 stub 函数,并且它工作得很好,但是当我尝试 stub 我自己的函数时,我似乎无法让它工作。请参阅以下简单示例:
test.js:
var myFunctions = require('../index')
var testStub = sinon.stub(myFunctions, 'testFunction')
testStub.returns('Function Stubbed Response')
....
myFunctions.testFunction() // is original response
index.js:
exports.testFunction = () => {
return 'Original Function Response'
}
最佳答案
我认为你的做法是正确的。
例如,我是按如下方式完成的,
index.js
exports.testFunction = () => {
return 'Original Function Response'
}
index.test.js
const sinon = require('sinon');
const chai = require('chai');
const should = chai.should();
const myFunctions = require('./index');
describe('myFunction', function () {
it('should stub', () => {
sinon.stub(myFunctions, 'testFunction').returns('hello');
let res = myFunctions.testFunction();
myFunctions.testFunction.callCount.should.eql(1);
res.should.eql('hello');
myFunctions.testFunction.restore();
res = myFunctions.testFunction();
res.should.eql('Original Function Response');
});
});
Result
myFunction
✓ should stub
1 passing (12ms)
关于javascript - Mocha 中的Sinon Stub 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44222831/