如何单元测试$位置服务search()方法,在AngularJS?单元测试、位置、方法、search

2023-09-13 04:19:19 作者:无所畏惧的小超人╰つ

如何建立AngularJS $位置服务搜索()方法的单元测试?

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

我是用茉莉花+噶用于测试和AngularJS 1.3,和单元测试是新的对我说:)

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

这是我的服务,这是在生产工作正常BTW:

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;
   });
})()

这是我serviceSpec:

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?

推荐答案

根据意见你需要一个 $ location.search()。ID 检查控制器功能,在这种情况下,最好的选择是使用 spyOn 上注入服务(任何真正的服务)

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

和记住的一些服务/指令需要 $ scope.digest()来触发和变化值

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

 
精彩推荐
图片推荐