with-sandbox
v1.0.0
Published
Mocha utility for sandboxing tests
Downloads
4
Maintainers
Readme
with-sandbox
Utility for sandboxing all of your mocha tests.
Tested on node v4.2.5-v5.10.1, v6.11.0, and v8.1.2.
Usage
Define your sandbox
config.js
const configureSandbox = require('with-sandbox');
module.exports.withSandbox = configureSandbox({
create: function() {
// return a sandbox object with any properties you want here
// runs once before the block wrapped with `withSandbox`
return {
sinon: sinon.sandbox(),
}
},
restore: function(sandbox) {
// restore everything on the sandbox
// runs after every test in the block wrapped with `withSandbox`
sandbox.sinon.restore();
}
});
Use your sandbox
test.js
const withSandbox = require('./config.js');
describe('Some test', withSandbox(function(sandbox) {
beforeEach(function() {
// you can now access your sandbox
// your sandbox will be restored after each test in the block
});
}));
Why not use before and afterEach?
Some people create sandboxes like this:
before(() => {
this.sandbox = { sinon: sinon.sandbox.create() };
});
afterEach(() => {
this.sandbox.sinon.restore();
});
This does not allow you to access the sandbox everywhere you might want to:
describe('someTest', function() {
// These will not work
def('myFunc', () => this.sandbox.sinon.stub()); // bdd-lazy-var
let myFunc = this.sandbox.sinon.stub();
});
withSandbox
allows you to access the sandbox more easily:
describe('something', withSandbox(function(sandbox) {
// These will both work
def('myFunc', () => sandbox.sinon.stub()); // bdd-lazy-var
let myFunc = sandbox.sinon.stub();
}));