我对sinon不再感兴趣并重新布线。我正在尝试检查是否在promise中调用了私有函数。存根的私有函数被调用,但是sinon没有检测到该调用。下面是我的代码片段。
var fileController = rewire('./file')
var stub = sinon.stub().returns("abc")
fileController.__set__('privFunc', stub)
fileController.sampleFunc()
expect(stub).to.be.called
let otherFile = require('otherFile')
var privFunc = function(data) {
}
var sampleFunc = function() {
otherFile.buildSomeThing.then(function(data) {
privFunc(data)
})
}
module.exports = {sampleFunc}
在上面的代码片段中,privFunc实际上被调用了。存根被调用,但是sinon无法检测到呼叫。
var privFunc = function(data) {
}
var sampleFunc = function() {
privFunc(data)
}
module.exports = {sampleFunc}
但是上面的代码片段可以正常工作。即。直接调用私有函数时
答案 0 :(得分:0)
您的otherFile.buildSomeThing
是异步的,您需要先等待它,然后再检查是否已调用privFunc
存根。
例如:
file.js
let otherFile = require('otherFile')
var privFunc = function(data) {
}
var sampleFunc = function() {
return otherFile.buildSomeThing.then(function(data) {
privFunc(data)
})
}
module.exports = {sampleFunc}
file.test.js
var fileController = rewire('./file')
var stub = sinon.stub().returns("abc")
fileController.__set__('privFunc', stub)
fileController.sampleFunc().then(() => {
expect(stub).to.have.been.called;
});
如果您使用的是摩卡咖啡,则可以使用以下内容:
describe('file.js test cases', () => {
let stub, reset;
let fileController = rewire('./file');
beforeEach(() => {
stub = sinon.stub().returns("abc");
reset = fileController.__set__('privFunc', stub);
});
afterEach(() => {
reset();
});
it('sampleFunc calls privFunc', async () => {
await fileController.sampleFunc();
expect(stub).to.have.been.called;
});
});