Cleaning up sinon stubs easily
Sinon provides this functionality through the use of Sandboxes, which can be used a couple ways:
// manually create and restore the sandboxvar sandbox;beforeEach(function () { sandbox = sinon.sandbox.create();});afterEach(function () { sandbox.restore();});it('should restore all mocks stubs and spies between tests', function() { sandbox.stub(some, 'method'); // note the use of "sandbox"}
or
// wrap your test function in sinon.test()it("should automatically restore all mocks stubs and spies", sinon.test(function() { this.stub(some, 'method'); // note the use of "this"}));
Previous answers suggest using sandboxes
to accomplish this, but according to the documentation:
Since sinon@5.0.0, the sinon object is a default sandbox.
That means that cleaning up your stubs/mocks/spies is now as easy as:
var sinon = require('sinon');it('should do my bidding', function() { sinon.stub(some, 'method');}afterEach(function () { sinon.restore();});
An update to @keithjgrant answer.
From version v2.0.0 onwards, the sinon.test method has been moved to a separate sinon-test
module. To make the old tests pass you need to configure this extra dependency in each test:
var sinonTest = require('sinon-test');sinon.test = sinonTest.configureTest(sinon);
Alternatively, you do without sinon-test
and use sandboxes:
var sandbox = sinon.sandbox.create();afterEach(function () { sandbox.restore();});it('should restore all mocks stubs and spies between tests', function() { sandbox.stub(some, 'method'); // note the use of "sandbox"}