Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 357
Dov Rosenberg Avatar asked Oct 24 '25 07:10

Dov Rosenberg


1 Answers

The structure of your test spec should look something like this:

describe("A spec (with setup and tear-down)", function() {
  var sandbox;

  beforeEach(function() {
    sandbox = sinon.sandbox.create();
    sandbox.stub(globalVar, "method", function() { return 1; });
  });

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

  it("should test1", function() {
    ...
  });

  it("should test2", function() {
    ...
  });
});

Or you could do this:

function test1() {
  ...
}

function test2() {
  ...
}

describe("A spec (with setup and tear-down)", function() {
  describe("test1", test1);
  describe("test2", test2);
});
like image 182
Ad.Infinitum Avatar answered Oct 26 '25 22:10

Ad.Infinitum