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
})
I'm posting this answer to address the comment in OP @Tri-Vuong's code - which was my main reason for my visiting this page:
None of the answers so far address this point, so I'll post what I've learned and summarize the other answers as well.
@Alissa called it correctly when she explained why it is a bad idea to set
isSpy
tofalse
- effectively spying on a spy resulting in the auto-teardown behavior of Jasmine no longer functioning as intended. Her solution (placed within the OP context and updated for Jasmine 2+) was as follows:The last
it
test demonstrates how one could change the behavior of an existing spy to something else besides original behavior: "and
-declare" the new behavior on the spyObj previously stored in the variable in thebeforeEach()
. The first test illustrates my use case for doing this - I wanted a spy to behave a certain way for most of the tests, but then change it for a few tests later.For earlier versions of Jasmine, change the appropriate calls to
.andCallFake(
,.andCallThrough()
, and.andReturnValue(
respectively.setting
isSpy
tofalse
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
you can clear all spies by calling
this.removeAllSpies()
(this
- spec)Or you can do it
In this case you use the same Spy but just change the var that it will return..
In Jasmine 2, the spy state is held in a SpyStrategy instance. You can get hold of this instance calling
$.ajax.and
. See the Jasmine source code on GitHub.So, to set a different fake method, do this:
To reset to the original method, do this: