【发布时间】: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