有没有一种方法可以轻松地重置所有sinon间谍、模拟和存根,以便与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发布于 2012-12-26 21:55:40
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"
}));发布于 2019-03-20 07:45:48
以前的答案建议使用sandboxes来完成此任务,但根据the documentation的说法
从sinon@5.0.0开始,sinon对象是默认的沙箱。
这意味着清理存根/模拟/间谍现在很容易:
var sinon = require('sinon');
it('should do my bidding', function() {
sinon.stub(some, 'method');
}
afterEach(function () {
sinon.restore();
});发布于 2017-04-19 11:30:14
@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"
} https://stackoverflow.com/questions/11552991
复制相似问题