mercredi 10 août 2016

Sinon.js stubbing a method when running test simultaneously

Let's consider the following function:

var dependency = require('dependency'); 
function func(options) {
    if (a) {
        ...
        return;
    }
    dependency.logic(options, func(err, res) {
        ...
    });
}

Now I have 2 test cases one for checking the if branch and one calling dependncy.logic() and checking its callback.

Case 1:

it('case 1', function() {
    ...
});

Case 2:

it('case 2', function(done) {
    this.sinon.stub(dependency, 'logic', function(options, callback) {
        // mock the dependency.logic() function to save time on I/O bound-task 
        // and to make sure the test works offline (network request)
        callback(someErr, someRes);
    });
    ...
});

Now this works fine when running separately, problem is when running simultaneously because case1 is interfering with the dependncy.logic() stub, and so the function is not mocked because it was first require()ed in the case1 test and so the mock didn't really work making the second case fail.

What should I do in such situation ? Also, I know I should've separated the callback to a different function, but I can't because it can potentially use arguments from func() to call it recursively.

Aucun commentaire:

Enregistrer un commentaire