4

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?

Community
  • 1
  • 1
Dov Rosenberg
  • 673
  • 6
  • 20

1 Answers1

2

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);
});
Ad.Infinitum
  • 316
  • 1
  • 7
  • But I'd like to be able to put these two specs in functions so I can reuse them for a variety of tests. And I'd like to have them be self contained so I don't have to create the sandbox and stubs code each time I call them. Is that not possible? – Dov Rosenberg Apr 28 '16 at 22:18
  • I see what you mean. Let me update my answer -- still new to formatting code in comments. – Ad.Infinitum Apr 28 '16 at 22:26
  • The extra describe wrapper - either as you have it or just inside each test function - does it. Extra tier of reporting, but as good as it appears is possible. Thanks. – Dov Rosenberg Apr 28 '16 at 22:42
  • This doesn't help sinon not re-wrapping already wrapped methods when tests are async – vsync Apr 24 '23 at 09:15