use*_*437 2 unit-testing jasmine angularjs 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;
});
})()
Run Code Online (Sandbox Code Playgroud)
这是我的服务规范:
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.
})
});
Run Code Online (Sandbox Code Playgroud)
当我使用search()方法时,我得到的是未定义的?如何在单元测试中使用该方法?
mau*_*ycy 10
根据评论你需要$location.search().id检查控制器功能,在这种情况下,最好的选择是使用spyOn注入服务(任何服务真的)
spyOn($location, 'search').andReturn({ id: mockedid })
Run Code Online (Sandbox Code Playgroud)
并记住需要$scope.digest()触发一些服务/指令并改变价值
| 归档时间: |
|
| 查看次数: |
4546 次 |
| 最近记录: |