首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >轻松清理sinon存根

轻松清理sinon存根
EN

Stack Overflow用户
提问于 2012-07-19 10:10:38
回答 9查看 101.9K关注 0票数 154

有没有一种方法可以轻松地重置所有sinon间谍、模拟和存根,以便与mocha的beforeEach块干净利落地工作。

我知道沙箱是一种选择,但我不知道如何使用沙箱来实现这一点。

代码语言:javascript
复制
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
EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2012-12-26 21:55:40

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

代码语言:javascript
复制
// 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"
}

代码语言:javascript
复制
// 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"
}));
票数 317
EN

Stack Overflow用户

发布于 2019-03-20 07:45:48

以前的答案建议使用sandboxes来完成此任务,但根据the documentation的说法

从sinon@5.0.0开始,sinon对象是默认的沙箱。

这意味着清理存根/模拟/间谍现在很容易:

代码语言:javascript
复制
var sinon = require('sinon');

it('should do my bidding', function() {
    sinon.stub(some, 'method');
}

afterEach(function () {
    sinon.restore();
});
票数 90
EN

Stack Overflow用户

发布于 2017-04-19 11:30:14

@keithjgrant答案的更新。

从版本v2.0.0开始,sinon.test方法已移至a separate sinon-test module。要使旧的测试通过,您需要在每个测试中配置这个额外的依赖项:

代码语言:javascript
复制
var sinonTest = require('sinon-test');
sinon.test = sinonTest.configureTest(sinon);

或者,您可以不使用sinon-test而使用sandboxes

代码语言:javascript
复制
var 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"
} 
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11552991

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档