有没有办法轻松重置所有的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
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"
}));
对@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"
}
您可以使用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');
}
以前的答案建议使用sandboxes
来实现这一目标,但根据the documentation:
从[email protected]开始,sinon对象是默认的沙箱。
这意味着清理存根/模拟/间谍现在就像以下一样简单:
var sinon = require('sinon');
it('should do my bidding', function() {
sinon.stub(some, 'method');
}
afterEach(function () {
sinon.restore();
});
如果你想要一个将有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)
})
请注意,当使用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');
}
);
restore()
只是恢复存根功能的行为,但它不会重置存根的状态。你必须用sinon.test
包装测试并使用this.stub
或在存根上单独调用reset()