aus*_*nbv 126 javascript testing mocha.js stubbing sinon
有没有办法轻松重置所有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
Run Code Online (Sandbox Code Playgroud)
kei*_*ant 287
兴农提供通过使用此功能沙箱,可用于几个方面:
// 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"
}
Run Code Online (Sandbox Code Playgroud)
要么
// 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"
}));
Run Code Online (Sandbox Code Playgroud)
Myk*_*lis 20
先前的答案建议使用sandboxes来完成此操作,但根据文档:
从sinon@5.0.0开始,sinon对象是默认的沙箱。
这意味着清理存根/模拟/间谍现在变得很容易:
var sinon = require('sinon');
it('should do my bidding', function() {
sinon.stub(some, 'method');
}
afterEach(function () {
sinon.restore();
});
Run Code Online (Sandbox Code Playgroud)
ana*_*and 11
对@keithjgrant的更新回答.
从版本V2.0.0起,sinon.test方法已被转移到一个独立的sinon-test模块.要使旧测试通过,您需要在每个测试中配置此额外依赖项:
var sinonTest = require('sinon-test');
sinon.test = sinonTest.configureTest(sinon);
Run Code Online (Sandbox Code Playgroud)
或者,您没有sinon-test并使用沙箱:
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"
}
Run Code Online (Sandbox Code Playgroud)
Dim*_*bas 10
您可以使用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');
}
Run Code Online (Sandbox Code Playgroud)
如果您想要一个具有sinon的设置,请务必在所有测试中将自身重置:
在helper.js中:
import sinon from 'sinon'
var sandbox;
beforeEach(function() {
this.sinon = sandbox = sinon.sandbox.create();
});
afterEach(function() {
sandbox.restore();
});
Run Code Online (Sandbox Code Playgroud)
然后,在您的测试中:
it("some test", function() {
this.sinon.stub(obj, 'hi').returns(null)
})
Run Code Online (Sandbox Code Playgroud)