javascript - 轻松清理 sinon stub

标签 javascript testing mocha.js stubbing sinon

有没有一种方法可以轻松地重置所有 sinon spy 模拟和 stub ,这些模拟和 stub 可以与 mocha 的 beforeEach block 一起干净地工作。

我看到沙盒是一个选项,但我不知道如何为此使用沙盒

beforeEach ->
  sinon.stub some, 'method'
  sinon.stub some, 'mother'

afterEach ->
  # I want to avoid these lines
  some.method.restore()
  some.other.restore()

it 'should call a some method and not other', ->
  some.method()
  assert.called some.method

最佳答案

Sinon 通过使用 Sandboxes 提供此功能,可以通过几种方式使用:

// manually create and restore the sandbox
var sandbox;
beforeEach(function () {
    sandbox = sinon.sandbox.create();
});

afterEach(function () {
    sandbox.restore();
});

it('should restore all mocks stubs and spies between tests', function() {
    sandbox.stub(some, 'method'); // note the use of "sandbox"
}

// wrap your test function in sinon.test()
it("should automatically restore all mocks stubs and spies", sinon.test(function() {
    this.stub(some, 'method'); // note the use of "this"
}));

关于javascript - 轻松清理 sinon stub ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11552991/

相关文章:

testing - 为什么smallCheck的 `Series`类在构造函数中有两个类型?

javascript - 如何使用 Sinon 创建测试替身来阻止实际函数的执行

JavaScript 的 Date.now() 返回 0(零)

javascript - 在错误的类别中显示数据对象

python - PyTorch:为什么在训练时期循环内部或外部调用它后验证准确性会发生变化?

javascript - Angular2/ typescript : How to get an array of objects through Pipe?

javascript - 使用 sinon.fakeServer 获取夹具数据

node.js - 使用mocha调试NodeJs程序时出错

javascript - 使用 Javascript 中的 regex 或 indexOf 更改字符串中的特定字符(转义字符)

javascript - Fido U2F 客户端 JavaScript 源代码