jeudi 28 avril 2016

how do I use sinon sandboxes when tests run asynchronously?

I've got some code I'm trying to test with a structure like this (per Cleaning up sinon stubs easily):

function test1() {
    // manually create and restore the sandbox
    var sandbox;
    beforeEach(function () {
        sandbox = sinon.sandbox.create();
        sandbox.stub(globalVar, "method", function() { return 1; });
    });

    afterEach(function () {
        sandbox.restore();
    });

    it('tests something', function(done) {
        anAsyncMethod(function() { doSomething(); done(); });
    }
 }

There is then a similar test2() function.

But if I do:

describe('two tests', function() {
    test1();
    test2();
}

I get:

TypeError: Attempted to wrap method which is already wrapped

I've done some logging to figure out the run order and it appears that the the issue is that it runs the test1 beforeEach() hook, then the test2 beforeEach() hook, then the test1 it(), etc. Because it's calling the second beforeEach() before it gets to the afterEach() from the first test, we have a problem.

Is there a better way I should be structuring this?

Aucun commentaire:

Enregistrer un commentaire