2012-07-19 83 views
107

有沒有一種方法可以輕鬆地重置所有的sinon spys mock和存根,這些都可以用摩卡的beforeEach塊清理工作。很容易清理sinon存根

我看到沙盒是一種選擇,但我不看你如何使用沙箱這個

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 

回答

246

興農通過使用Sandboxes,可以使用幾種方法提供了這種功能:

​​

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

如果我讀的http:// sinonjs .org/docs /#sinon-test正確地在你的'sinon.test'例子中,你應該使用'this.stub(some,'method');' – EvdB 2013-05-29 07:53:23

+0

@EvdB You'e right。固定。我*認爲*使用'sinon.stub()'也可以,但更好地發揮它的安全性並堅持它的記錄方式。 – keithjgrant 2013-05-30 21:09:22

+1

它似乎是強制性的:「如果你不想手動restore()',你必須使用'this.spy()'而不是'sinon.spy()'(和'stub','mock ')「。 – 2013-06-12 07:14:52

9

如在01所示。您可以使用sinon.collection博客文章(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'); 
} 
3

注意,使用qunit而不是摩卡時,你需要一個模塊,例如在包裝這些

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

qunit 2正在切換到'beforeEach'和'afterEach'。 'setup'和'teardown'方法將被棄用。 – 2015-01-29 17:09:04

2

restore()剛剛恢復的存根功能的行爲,但它不重置存根的狀態。你必須要麼sinon.test包裝你的測試和使用this.stub或單獨的存根

4

reset()如果你想有一個設置,將有興農總是自行復位所有測試:

在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) 
}) 
8

@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" 
} 
+1

或者您可以實際使用sinon-test包並像以前一樣繼續您的代碼:-D – oligofren 2017-06-16 11:55:27