当使用 Sinon.js 创建模拟时, mock.restore() 实际上做了什么?

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

我已经开始使用 Sinon.js 在 Mocha 测试套件中模拟 MongoDB 库。我很困惑为什么我的 afterEach 块中的 mock.restore() 实际上没有清除我在其他测试中设置的模拟和断言。示例:

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

最后一行将抛出 Expected updateCustomer([...]) once (never called) ExpectationError。在 the documentation 中表示 mock.restore() "Restores all mocked methods"。我试图弄清楚这到底意味着什么,因为它并没有清除我之前的期望,即使看起来我已经用其他东西覆盖了该方法的模拟。想法?

总结

如果任何方法已被模拟包装在代理中,restore() returns 将它们恢复到原始状态。仅此而已。

详情

查看 the source 得到以下信息:

  • 如果尚未设置 expectations,则调用 expects() 为该方法设置一个 proxy,然后添加一个 expectation
  • 调用 verify() 循环对代理的期望并验证每个,然后调用 restore()
  • restore() 循环代理并恢复原始方法

restore() 所做的只是删除 expects() 添加的任何代理,它不会影响模拟存储的 expectations

因此对于示例代码中的每一行:

  1. updateCustomer 创建代理并添加 expectation of once
  2. 恢复原状updateCustomer
  3. never 中的 expectation 添加到 updateCustomer
  4. 循环updateCustomer上的两个expectations记录once失败,调用restore(),然后报告once失败