简体   繁体   English

无法使用Mocha / Sinon模拟/存根函数

[英]Function can not be mocked/stub with Mocha/Sinon

I want to test function B in the following codes to catch exception thrown from function A 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);

However, it seems the function A can NOT be mocked with following codes, as the original function A still be called here. 然而,似乎功能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();
});

Also it does not work in another way with stub 同样,它不能与stub以其他方式一起使用

    _A = sinon.stub(myModule, 'A');
    _A.onCall(0).throws(new Error('for test'));

Could someone help me figure out what wrong with my codes? 有人可以帮我弄清楚我的代码有什么问题吗?

The problem is that your reference to A in the body of B is referencing the original A directly. 问题是,你提到A在体内B被引用原来A直接。 If you instead reference this.A , it should call the stub wrapped 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM