简体   繁体   中英

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 .

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.

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

    _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. If you instead reference this.A , it should call the stub wrapped 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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