lundi 27 juillet 2015

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?

Aucun commentaire:

Enregistrer un commentaire