问题
How to create a unit test of AngularJS $location service search() method?
I am using Jasmine+Karma for the test and AngularJS 1.3, and unit test is new to me :)
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;
});
})()
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?
回答1:
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 })
and remember that some of the services/directives needs $scope.digest()
to be triggered and change value
来源:https://stackoverflow.com/questions/27360814/how-to-unit-test-location-service-search-method-in-angularjs