我有以下测试;
var request = require('superagent');
beforeEach(function (done) {
this.clock = sinon.useFakeTimers();
done();
});
afterEach(function (done) {
this.clock.restore();
done();
});
it("should return user", function (done) {
var authCookie = "validCookie";
var res = { /*some custom response here*/};
var getRequest = sinon.stub(request, "get");
getRequest.returns(res);
Auth.GetUserViaApi(authCookie, callback);
this.clock.tick(510);
var args = callback.args;
var user = args[0][1];
expect(user.stat).to.equal("success");
});
it("should return error", function (done) {
var authCookie = "notValidCookie";
var res = { /*some custom response here*/};
var getRequest = sinon.stub(request, "get");
getRequest.returns(res);
Auth.GetUserViaApi(authCookie, callback);
this.clock.tick(510);
var args = callback.args;
var error = args[0][0];
expect(error.stat).to.equal("fail");
});
it("should return server not available", function (done) {
var authCookie = "breakingCookie";
var res = { /*some custom response here*/};
var getRequest = sinon.stub(request, "get");
getRequest.returns(res);
Auth.GetUserViaApi(authCookie, callback);
this.clock.tick(510);
var args = callback.args;
var error = args[0][0];
expect(error.stat).to.equal("notAvailable");
});
如果我单独运行它们,所有测试都会通过,但是当我尝试运行它们时, 我认为存根在被其他函数初始化之前就会被使用。
例如,第3个函数是从第2个函数获得存根响应。
如何确保每个函数都有自己的存根获取请求?
答案 0 :(得分:1)
使用sinon
存根方法时,必须确保在完成后恢复该方法。
var myObject = require('my-object');
describe('using a stub', function () {
var myStub;
beforeEach(function () {
myStub = sinon.stub(myObject, 'method');
});
afterEach(function () {
myStub.restore();
});
it('uses my stub', function () {
myStub.returns(/* some return value */)
// act, assert
});
});