Jax
Jax

Reputation: 1843

Angular JS-Jasmine how to unit test $location.path().search()?

been doing some googling but cant find an answer to this little problem of mine. Just trying to test this bit of code from my controller:

$scope.viewClientAssets = (id) -> 
  $location.path("/assets").search("client_id", "#{id}") 

which in turn returns this url:

http://localhost:3000/admin#/assets?client_id=19

this all works fine however when unit testing......A few assumptions: I have my spec set up correctly as I have other tests and expectations working perfectly fine so here is the test:

it 'checks if view client assets path is correct', ->
    createController()
    #gets rid of unnecessary function calls
    flushRequests()
    #calls the ctrl function with necessary args
    $scope.viewClientAssets(clientData.client.id)
    spyOn($location, 'path')
    spyOn($location, 'search') #tried diff methods here such as 
    # and.returnValue(), .calls.any(), calls.all()
    expect($location.path).toHaveBeenCalledWith("/assets")
    expect($location.path.search).toHaveBeenCalled()

all other tests pass however when this gets hit I get the following error:

TypeError: Cannot read property 'search' of undefined

the console debugger tells me:

$scope.createClientAsset = function(id) {
        return $location.path('/assets/create').search("client_id", "" + id);
      };

that path is undefined?

any ideas anyone?

Upvotes: 3

Views: 4748

Answers (2)

killyosaur
killyosaur

Reputation: 93

To test the spyOn, for search, do the following

spyOn($location, 'path').and.callThrough();
spyOn($location, 'search');

That will return values correctly.

Upvotes: 4

Peter Ashwell
Peter Ashwell

Reputation: 4302

You are spying on $location.path and not returning anything, or returning undefined.

Make your spy return a string (the string you would normally expect, the actual path) and the search function, defined for all strings in javascript, will work normally in your test.

e.g. Do as follows:

spyOn($location, 'path').and.returnValue('/client_id/')
$location.path('anything'); // returns '/client_id/'

Upvotes: 2

Related Questions