Teoman shipahi
Teoman shipahi

Reputation: 23132

Stubbed request getting shared over multiple tests functions

I have following test;

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

if I run them individually all tests are passing, but when I try to run them all, I think stubs are getting used before it is initialized by other function.

For example 3rd function is getting stubbed response from 2nd function.

How can I make sure each function will have their own stubbed get request?

Upvotes: 0

Views: 96

Answers (1)

thebearingedge
thebearingedge

Reputation: 681

When you use sinon to stub a method, you have to be sure to restore the method when you are done.

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
  });

});

Upvotes: 1

Related Questions