Is there a way to easily reset all sinon spys mocks and stubs that will work cleanly with mocha\'s beforeEach blocks.
I see sandboxing is an option but I do not see
Create a sandbox which will act as a black box container for all your spies, stubs, mocks and fakes.
All you have to do is create a sandbox in the very first describe block so that, it is accessible throughout all the test cases. And once you are done with all the test cases you should release the original methods and clean up the stubs using the method sandbox.restore()
in the afterEach hook so that at runtime it releases held up resources afterEach
test case is passed or failed.
Here is an example:
describe('MyController', () => {
//Creates a new sandbox object
const sandbox = sinon.createSandbox();
let myControllerInstance: MyController;
let loginStub: sinon.SinonStub;
beforeEach(async () => {
let config = {key: 'value'};
myControllerInstance = new MyController(config);
loginStub = sandbox.stub(ThirdPartyModule, 'login').resolves({success: true});
});
describe('MyControllerMethod1', () => {
it('should run successfully', async () => {
loginStub.withArgs({username: 'Test', password: 'Test'}).resolves();
let ret = await myControllerInstance.run();
expect(ret.status).to.eq('200');
expect(loginStub.called).to.be.true;
});
});
afterEach(async () => {
//clean and release the original methods afterEach test case at runtime
sandbox.restore();
});
});
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');
}