裏面我有一個服務這個方法: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