[英]Function can not be mocked/stub with Mocha/Sinon
我想在以下代碼中測試函數B
,以捕獲使用Mocha/Sinon
從函數A
引發的異常。
MyModule.js
(function(handler) {
// export methods
handler.B = B;
handler.A = A;
function A() {
// the third party API is called here
// some exception may be thrown from it
console.log('function A is invoked...');
}
function B() {
console.log('function B is invoked...');
try {
A();
} catch (err) {
console.log('Exception is ' + err);
}
}
})(module.exports);
然而,似乎功能A
不能與下面的代碼被嘲笑,因為原有功能A
仍然在這里調用。
var myModule = require('MyModule.js');
var _A;
it('should catach exception of function A', function(done) {
_A = sinon.stub(myModule, 'A', function() {
throw new Error('for test');
});
myModule.B();
_A.restore();
done();
});
同樣,它不能與stub
以其他方式一起使用
_A = sinon.stub(myModule, 'A');
_A.onCall(0).throws(new Error('for test'));
有人可以幫我弄清楚我的代碼有什么問題嗎?
問題是,你提到A
在體內B
被引用原來A
直接。 如果您改為引用this.A
,則應調用存根包裝的A
(function(handler) {
// export methods
handler.B = B;
handler.A = A;
function A() {
// the third party API is called here
// some exception may be thrown from it
console.log('function A is invoked...');
}
function B() {
console.log('function B is invoked...');
try {
// This is referencing `function A() {}`, change it to `this.A();`
A();
} catch (err) {
console.log('Exception is ' + err);
}
}
})(module.exports);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.