Automatic sandbox setup and teardown for SinonJS
Instead of writing tedious setup and teardown code for each individual test case you can let Sinon do all the cleanup for you.
So instead of doing this (using Mocha syntax):
var spy1;var spy2;;;
You could write just this
Sinon will take care of removing all the spies and stubs
from the wrapped functions for you. It does this by using
Do notice that we use a
function and not a arrow function (ES2015)
when wrapping the test with
sinon.test as it needs
to be able to access the
this pointer used inside
of the function, which using an arrow function would prevent.
See the Usage section for more details.
$ npm install sinon-test
Node and CommonJS build systems
Once initialized, the package creates a context for your test based on a sinon sandbox.
You can use
this in a wrapped test function to create sinon spies, stubs, etc.
After your test completes, the sandbox restores anything modified to its original value.
If your test function takes any arguments, pass then to the
after the test function. If the last argument is a function, it is assumed to be a callback
for an asynchronous test. The test function may also return a promise.
See the sinon documentation for more documentation on sandboxes.
sinon-test instances need to be configured with a
sinon instance (version 2+)
before they can be used.
var sinon = ;var sinonTest = ;var test = ;var assert = ;;
Direct browser usage
In place of the
require statements indicated above, in the
browser, you should simply reference the global
including a script tag in your HTML:
Or if you are in an ES6 Modules environment (modern browsers only), you only need to add an import statement:
const test = sinon;
In order to configure the sandbox that is created, a configuration hash can be passed as a 2nd argument to
const test = sinon useFakeTimers: false;
The only difference to the standard configuration object for Sinon's sandbox is the addition of the
injectIntoThis property, which is used to inject the sandbox' props into the context object (
Sinon 1.x used to ship with this functionality built-in, exposed as
sinon.test(). You can keep all your existing test code by configuring an instance of
sinon-test, as done above, and then assigning it to
sinon like this in your tests:
sinontest = test;