[英]sinon not detecting private function called inside promise
我不喜歡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}
但這上面的代碼片段效果很好。 即。 直接調用私有函數時
您的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;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.