首页 > 解决方案 > 使用 Sinon.js 创建 mocks 时,mock.restore() 究竟做了什么?

问题描述

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

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

最后一行将抛出一个Expected updateCustomer([...]) once (never called)ExpectationError。在文档中它说mock.restore()“恢复所有模拟方法”。我试图弄清楚这实际上意味着什么,因为它并没有清除我之前的期望,即使看起来我已经用其他东西覆盖了该方法的模拟。想法?

标签: javascriptunit-testingmocha.jssinon

解决方案


概括

如果任何方法已被模拟包装在代理中,则将restore()它们返回到其原始状态。这就是它所做的一切。

细节

查看源代码提供以下信息:

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

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

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

  1. 创建代理updateCustomer并添加expectationonce
  2. 恢复原状updateCustomer
  3. 添加到expectation_neverupdateCustomer
  4. 循环这两个expectationsupdateCustomer记录once失败,调用restore(),然后报告once失败

推荐阅读