chai-spies
chai-spies copied to clipboard
Bring back spy.reset()
A previous issue https://github.com/chaijs/chai-spies/issues/27 introduced the reset method to this library which we use extensively. It was removed in 1.0 for no clear reason. I'd like to see it put back
@AdamMcCormick can you use restore instead?
chai.spy.restore()
@dabutvin No. Please see the thread at #27. Restore is not the same thing and does not satisfy my use case. It also makes my tests significantly slower given my test setup.
Any update on this issue?
Hey @AdamMcCormick thanks for the issue.
It was removed as it was seen to be an anti pattern because it swaps out internal state which can cause issues in tests - certainly compounding issues if your tests rely on external state. The preferred alternative is to restore
and make a new spy.
@AdamMcCormick could you please give us some numbers as to how much slower your tests are by using restore? I'd be surprised to see even 100ms delta between restore/reset.
You can just do
const spy = () => chai.spy()
let funcToBeSpied
beforeEach(() => {
funcToBeSpied = spy()
})
With proxyquire
you have to clear the require
cache and re-proxyquire
the module, in order to do a full reset.
That is quite messy. This was my solution for resetting the spy, in lieu of spy.reset()
:
let barSpy;
const foo = proxyquire("../lib/foo.js", {
"./bar.js": (...args) => barSpy(...args),
});
describe("foo bar", () => {
beforeEach(() => {
barSpy = chai.spy();
});
it("bar is called once by foo", () => {
foo();
expect(barSpy).to.have.been.called.once;
});
it("bar is called once by foo, again", () => {
foo();
expect(barSpy).to.have.been.called.once;
});
});