Jasmine SpyOn same method more than once

Viewed 14353

I have an angular controller with a method that calls $location.search() twice.

First time is just $location.search() to return the value.
Second time is $location.search("foo", null) to clear it.

I have the following spy in my unit test:
spyOn($location, "search").and.returnValue({ foo: "bar" });

It appears the spy returns {foo:"bar"} even when my implementation does $location.search("foo", null).

I need a way to have two different spies for the same method depending on the arguments.

I need this expect:
expect($location.search().foo).toEqual(null);
to pass at the end of the unit test.

2 Answers

Also it's possible to call spy properties on the mocked object directly. The code may look like:

spyOn($location,'search');

$location.search.and.returnValue(null);
// do stuff
$location.search.and.returnValue({ foo: "bar" })
// do other stuff

In case of typescript it may look like:

spyOn($location,'search');

(<jasmine.Spy>$location.search).and.returnValue(null);
// do stuff
(<jasmine.Spy>$location.search).and.returnValue({ foo: "bar" })
// do other stuff

Posting this answer because it may look a bit cleaner and doesn't require additional variables.

Related