How to unit test $location service search() method, in AngularJS?

[亡魂溺海] 提交于 2019-12-21 22:11:19

问题


How to create a unit test of AngularJS $location service search() method?

I am using Jasmine+Karma for the test and AngularJS 1.3, and unit test is new to me :)

This is my service, which is working fine in production btw:

'use strict';
(function () {
angular.module('myApp')
   .service('myService', function ($location) {
      var _customerId = $location.search().id;
      /*jshint validthis:true */
      this.customerId = _customerId;
   });
})()

And this is my serviceSpec:

describe('Service: mySerivce', function(){

 var $location;

 beforeEach(module('myApp'));

 beforeEach(inject(function(_$location_){
  $location = _$location_;
 }));

 it('should get ID from url', function(){
   $location.path('/?id=1080');

   console.log($location.path()); // logs: '/?id=1080'
   console.log($location.search().id); // logs: undefined

   expect($location.search().id).toEqual(1080); // Returns err msg Expected undefined to equal 1080.
  })

});

When i use the search() method all I get is undefined? How can i use the method in a unit test?


回答1:


As per comments you need a $location.search().id to check controller functionality, in that case the best option is to use spyOn on injected service (any service really)

spyOn($location, 'search').andReturn({ id: mockedid })

and remember that some of the services/directives needs $scope.digest() to be triggered and change value



来源:https://stackoverflow.com/questions/27360814/how-to-unit-test-location-service-search-method-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!