轻松清理sinon存根

问题描述 投票:120回答:7

有没有办法轻松重置所有的sinon spys模拟和存根,它们将与mocha的beforeEach块一起干净地工作。

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

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
javascript testing mocha stubbing sinon
7个回答
281
投票

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"
}));

11
投票

对@keithjgrant的更新回答。

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

var sinonTest = require('sinon-test');
sinon.test = sinonTest.configureTest(sinon);

或者,你没有sinon-test并使用sandboxes

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"
} 

10
投票

您可以使用sinon.collection,如this博客文章(2010年5月)由sinon图书馆的作者所示。

sinon.collection api已经改变,使用它的方法如下:

beforeEach(function () {
  fakes = sinon.collection;
});

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

it('should restore all mocks stubs and spies between tests', function() {
  stub = fakes.stub(window, 'someFunction');
}

10
投票

以前的答案建议使用sandboxes来实现这一目标,但根据the documentation

[email protected]开始,sinon对象是默认的沙箱。

这意味着清理存根/模拟/间谍现在就像以下一样简单:

var sinon = require('sinon');

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

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

5
投票

如果你想要一个将有sinon的设置总是为所有测试重置自己:

在helper.js中:

import sinon from 'sinon'

var sandbox;

beforeEach(function() {
    this.sinon = sandbox = sinon.sandbox.create();
});

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

然后,在你的测试中:

it("some test", function() {
    this.sinon.stub(obj, 'hi').returns(null)
})

3
投票

请注意,当使用qunit而不是mocha时,您需要将它们包装在一个模块中,例如

module("module name"
{
    //For QUnit2 use
    beforeEach: function() {
    //For QUnit1 use
    setup: function () {
      fakes = sinon.collection;
    },

    //For QUnit2 use
    afterEach: function() {
    //For QUnit1 use
    teardown: function () {
      fakes.restore();
    }
});

test("should restore all mocks stubs and spies between tests", function() {
      stub = fakes.stub(window, 'someFunction');
    }
);

3
投票

restore()只是恢复存根功能的行为,但它不会重置存根的状态。你必须用sinon.test包装测试并使用this.stub或在存根上单独调用reset()

© www.soinside.com 2019 - 2024. All rights reserved.