【问题标题】:How to unit test $location service search() method, in AngularJS?如何在 AngularJS 中对 $location service search() 方法进行单元测试?
【发布时间】:2014-12-08 15:03:27
【问题描述】:

如何创建AngularJS $location service search()方法的单元测试?

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

这是我的服务,顺便说一句,在生产环境中运行良好:

'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() 方法时,我得到的都是未定义的?如何在单元测试中使用该方法?

【问题讨论】:

  • 是的,那么我仍然不确定。如何改为测试 customerId?
  • 首先你所做的测试没有多大意义,你只是测试 $location.path 本身,它已经被 AngularJS 测试过;) 为 $location.search() 反映变化您可能需要运行 $scope.$digest() 或使用 spyOn 来测试值
  • 将调查 spyOn :) 我正在测试搜索方法的原因是因为我想将它用于另一个测试。测试是使用 $httpBackend 进行的,我需要在 GET 请求中使用 ID。
  • 测试使用搜索的控制器,您可以这样做:spyOn($location, 'search').andReturn({id: 'mockedid'}),您可以在其中检查对后端的调用是否包含此 mockedid
  • 谢谢!成功了:)

标签: angularjs unit-testing jasmine karma-runner


【解决方案1】:

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

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

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

【讨论】:

  • 请注意,如果您使用 Jasmine 2.0+ 版,请注意,如果您使用的是 .and.returnValue() 而不是 .andReturn()
  • spyOn($location, 'search').andCallFake(function() {}); // 也很方便!
猜你喜欢
  • 1970-01-01
  • 2012-11-19
  • 1970-01-01
  • 2014-09-21
  • 2014-04-06
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
  • 1970-01-01
相关资源
最近更新 更多