首页 文章

轻松清理sinon存根

提问于
浏览
115

有没有办法轻松重置所有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

6 回答

  • 4

    restore() 只是恢复存根功能的行为,但它不能用 sinon.test 包装您的测试并使用 this.stub 或在存根上单独调用 reset()

  • 10

    对@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"
    }
    
  • 3

    您可以使用sinon.collection,如sinon库的作者在this博客文章(2010年5月)中所示 .

    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');
    }
    
  • 3

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

    in helper.js:

    import sinon from 'sinon'
    
    var sandbox;
    
    beforeEach(function() {
        this.sinon = sandbox = sinon.sandbox.create();
    });
    
    afterEach(function() {
        sandbox.restore();
    });
    

    Then, in your test:

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

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

    请注意,当使用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');
        }
    );
    

相关问题