如何在AngularJS中单元测试$ location service search()方法?

时间:2014-12-08 15:03:27

标签: angularjs unit-testing jasmine karma-runner

如何创建AngularJS $位置服务search()方法的单元测试?

我使用Jasmine + Karma进行测试和AngularJS 1.3,单元测试对我来说是新的:)

这是我的服务,在生产中运行良好btw:

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

这是我的服务规范:

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.
  })

});

当我使用search()方法时,我得到的是未定义的?我如何在单元测试中使用该方法?

1 个答案:

答案 0 :(得分:10)

根据评论,您需要$location.search().id来检查控制器功能,在这种情况下,最好的选择是在注入服务上使用spyOn(真正的任何服务)

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

并记住,某些服务/指令需要触发$scope.digest()并更改值