chai-spies icon indicating copy to clipboard operation
chai-spies copied to clipboard

Bring back spy.reset()

Open AdamMcCormick opened this issue 6 years ago • 6 comments

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 avatar Aug 16 '18 20:08 AdamMcCormick

@AdamMcCormick can you use restore instead?

chai.spy.restore()

dabutvin avatar Sep 04 '18 22:09 dabutvin

@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.

AdamMcCormick avatar Sep 04 '18 23:09 AdamMcCormick

Any update on this issue?

zinoadidi avatar Sep 19 '19 03:09 zinoadidi

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.

keithamus avatar Sep 19 '19 10:09 keithamus

You can just do

const spy = () => chai.spy()
let funcToBeSpied

beforeEach(() => {
  funcToBeSpied = spy()
})

jorgeortega avatar Mar 05 '20 09:03 jorgeortega

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;
  });
});

Daghall avatar Dec 28 '20 23:12 Daghall