Matt Vukas
Matt Vukas

Reputation: 3295

When using Sinon.js to create mocks, what does mock.restore() actually do?

I've started using Sinon.js to mock a MongoDB library in a Mocha test suite. I'm confused as to why mock.restore() in my afterEach blocks do not actually clear out the mocks & assertions I've set up in other tests. Example:

mockedMongo.expects('updateCustomer').once();
mockedMongo.restore();
mockedMongo.expects('updateCustomer').never();
mockedMongo.verify(); // error here

The last line will throw an Expected updateCustomer([...]) once (never called) ExpectationError. In the documentation it says that mock.restore() "Restores all mocked methods". I'm trying to figure out what that actually means, since it doesn't clear out my previous expectation, even when it seems that I've overwritten the mock on that method with something else. Thoughts?

Upvotes: 1

Views: 411

Answers (1)

Brian Adams
Brian Adams

Reputation: 45840

Summary

If any methods have been wrapped in a proxy by the mock, restore() returns them to their original state. That's all it does.

Details

Looking at the source gives the following info:

  • calling expects() sets up a proxy for the method if no expectations have been set on it yet, and then adds an expectation
  • calling verify() cycles the expectations on the proxies and verifies each, then calls restore()
  • restore() cycles the proxies and restores the original methods

All restore() does is remove any proxies added by expects(), it doesn't affect the expectations stored by the mock.

So for each line in your example code:

  1. create proxy for updateCustomer and add expectation of once
  2. restore original updateCustomer
  3. add expectation of never to updateCustomer
  4. cycle the two expectations on updateCustomer and record that once fails, call restore(), then report that once failed

Upvotes: 2

Related Questions