里面我有一个服务这个方法:AngularJS测试一个承诺被称为一个承诺
this.getCoords = function() {
var deferred = $q.defer();
geolocation.getLocation().then(function(data) { // line 29 in Karma output
var coords = _.pick(data.coords, 'latitude', 'longitude');
return deferred.resolve(coords);
}, function(reason) {
return deferred.reject(reason);
});
return deferred.promise;
};
由于geolocation
本身就是一个模块,我只是想测试geolocation.getLocation()
承诺确实已被调用。
什么我迄今所做的:
...
geolocationGetLocationSpy = spyOn(geolocation, 'getLocation');
...
describe('getCoords()', function() {
it('should call geolocation.getLocation()', function() {
Googlemaps.getCoords(); // line 64 in Karma output
// promise won't get resolved until a digest
$rootScope.$apply();
expect(geolocationGetLocationSpy).toHaveBeenCalled();
});
});
但是我得到:
PhantomJS 1.9.2 (Mac OS X) Service: Googlemaps getCoords() should call geolocation.getLocation() FAILED
TypeError: 'undefined' is not an object (evaluating 'geolocation.getLocation().then')
at /Users/jviotti/Projects/Temporal/angular/angular-geolocation/app/scripts/services/googleMaps.js:29
at /Users/jviotti/Projects/Temporal/angular/angular-geolocation/test/spec/services/googleMaps.js:64
还有什么应该怎么办?
什么是geolocationGetLocationSpy?如果我想窥探'getLocation()'方法,我会这样做:'spyOn(goelocation,'getLocation');'在测试开始时。然后在最后你可以期待它被称为:'expect(geoLocation.getLocation).toHaveBeenCalled();' –
'geolocationGetLocationSpy = spyOn(geolocation,'getLocation');'。将间谍分配给变量具有相同的结果。几乎在所有的测试中都有这种模式。它应该工作。 – jviotti