gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:25:38 29 4
gpt4 key购买 nike

我已经开始使用 Sinon.js 在 Mocha 测试套件中模拟 MongoDB 库。我很困惑为什么我的 afterEach block 中的 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() “恢复所有模拟方法”。我试图弄清楚这到底意味着什么,因为它并没有清除我之前的期望,即使看起来我已经用其他东西覆盖了该方法的模拟。想法?

最佳答案

总结

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

详情

查看the source给出以下信息:

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

所有 restore() 所做的就是删除 expects() 添加的任何代理,它不会影响 mock 存储的 expectations .

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

  1. updateCustomer 创建代理并添加 onceexpectation
  2. 恢复原来的updateCustomer
  3. neverexpectation 添加到 updateCustomer
  4. updateCustomer上循环两个expectations并记录一次失败,调用restore(),然后报告一次失败

关于javascript - 使用 Sinon.js 创建模拟时,mock.restore() 实际上做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51989345/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com