How do we clear spy programmatically in Jasmine?

Tri Vuong picture Tri Vuong · Jan 16, 2012 · Viewed 73.6k times · Source

How do we clear the spy in a jasmine test suite programmatically? Thanks.

beforeEach(function() {
  spyOn($, "ajax").andCallFake(function(params){
  })
})

it("should do something", function() {
  //I want to override the spy on ajax here and do it a little differently
})

Answer

Alissa picture Alissa · May 18, 2014

setting isSpy to false is a very bad idea, since then you spy on a spy and when Jasmine clears the spies at the end of your spec you won't get the original method. the method will be equal to the first spy.

if are already spying on a method and you want the original method to be called instead you should call andCallThrough() which will override the first spy behavior.

for example

var spyObj = spyOn(obj,'methodName').andReturn(true);
spyObj.andCallThrough();

you can clear all spies by calling this.removeAllSpies() (this - spec)