javascript - 使用 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()
“恢复所有模拟方法”。我试图弄清楚这实际上意味着什么,因为它并没有清除我之前的期望,即使看起来我已经用其他东西覆盖了该方法的模拟。想法?
解决方案
概括
如果任何方法已被模拟包装在代理中,则将restore()
它们返回到其原始状态。这就是它所做的一切。
细节
查看源代码提供以下信息:
- 如果尚未设置方法,则调用为该方法
expects()
设置一个,然后添加一个proxy
expectations
expectation
- 调用
verify()
循环代理上的期望并验证每个,然后调用restore()
restore()
循环代理并恢复原始方法
所做restore()
的只是删除由添加的任何代理expects()
,它不会影响expectations
模拟存储的。
因此,对于示例代码中的每一行:
- 创建代理
updateCustomer
并添加expectation
once
- 恢复原状
updateCustomer
- 添加到
expectation
_never
updateCustomer
- 循环这两个
expectations
并updateCustomer
记录once
失败,调用restore()
,然后报告once
失败
推荐阅读
- javascript - 检查商店是否营业。MySQL node.js 业务逻辑
- angular - 垫日期开始日期结束日期验证角度8
- c++ - 如何使用 C++ 中的给定信息计算单身或已婚人士的税款
- visual-studio-code - 如何防止 VSCode 自动添加新行和缩进
- python-3.x - KeyError: 'axes.color_cycle 不是有效的 rc 参数(有关有效参数的列表,请参见 rcParams.keys())'
- php - 为什么 PHP 的 REQUEST 和 GET 会突然停止工作?
- javascript - 范围从 n 在两个方向
- javascript - 映射单选选项未按预期工作
- arrays - 合并列中的两个或多个“列表”?
- python - 无法点击下一页进行网页抓取