Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleaning up sinon stubs easily

People also ask

What does Sinon restore do?

Replaces the spy with the original method. Only available if the spy replaced an existing method. The highlighted sentence is the key. The restore functions in sinon only work on spies and stubs that replace an existing method, and our spy was created as an anonymous (standalone) spy.

What is Sinon sandbox?

var sandbox = sinon.The sinon. createSandbox(config) method is often an integration feature, and can be used for scenarios including a global object to coordinate all fakes through. Sandboxes are partially configured by default such that calling: var sandbox = sinon.


Sinon provides this functionality through the use of Sandboxes, which can be used a couple ways:

// manually create and restore the sandbox
var 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 [email protected], 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"
} 

You may use sinon.collection as illustrated in this blog post (dated May 2010) by the author of the sinon library.

The sinon.collection api has changed and a way to use it is the following:

beforeEach(function () {
  fakes = sinon.collection;
});

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

it('should restore all mocks stubs and spies between tests', function() {
  stub = fakes.stub(window, 'someFunction');
}