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?
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With