角度单元测试服务返回承诺茉莉花



我按照本教程对返回Promise但无法正常工作的服务进行了单元测试。

我的服务返回一个Promise,该将重新定位HTML5

app.factory('getGeo', function() { 
return function(){
return new Promise(function (resolve, reject) {
navigator.geolocation.getCurrentPosition(resolve, reject, options);
});        
}
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};         
});

我的控制器有一个功能,可以解析Promise以在应用程序中设置某些状态。

getGeo().then((position) => {
//perform logic when geo is received
$scope.weatherInfo.la = position.coords.latitude;//new properties
$scope.weatherInfo.lo = position.coords.longitude;//new properties
$scope.weatherInfo.url = `http://api.openweathermap.org/data/2.5/weather?lat=${$scope.weatherInfo.la}&lon=${$scope.weatherInfo.lo}&appid=0d00180d180f48b832ffe7d9179d40c4`;
})

而我的测试:

beforeEach(inject(function(_$rootScope_, _getGeo_){
$rootScope = _$rootScope_;
$getGeo = _getGeo_;
}));
describe('getGeo method', function() {
it('getGeo should return a promise', function() {
var $scope = $rootScope.$new();
var position = {coords:{coords:{latitude:'1',latitude:'3'}}};
$getGeo().then(function(position) {
expect($scope.weatherInfo.url).not.toBeNull();
done();
});
$scope.$digest();                
});
});

我得到了这个SPEC HAS NO EXPECTATIONS getGeo should return a promise.似乎模拟服务中的代码从未被调用。但是,如果我移出expect($scope.weatherInfo.url).not.toBeNull()并将其放在$scope.$digest()下,我会得到一个Cannot read property 'url' of undefined错误。

  1. var position = {coords:{coords:{latitude:'1',latitude:'3'}}}; $getGeo().then(function(position) { expect($scope.weatherInfo.url).not.toBeNull(); }

回调中的变量 - 它是承诺将返回的数据。这不是你的var position = {coords:{coords:{latitude:'1',latitude:'3'}}};

  1. 我认为你不应该在测试中打电话给工厂。当您第一次注入构造函数时,工厂只会调用一次构造函数。 所以你只需要做下一个

    $getGeo.then(function(position) {...})

  2. 您的工厂从外部获取数据navigator.geolocation.getCurrentPosition()。所以你需要为它制作存根。

    spyOn(navigator.geolocation, 'getCurrentPosition').andReturn(/* here is the data which you expected */)

很难向您展示完整的示例。但是,我试图描述关键的事情。

最新更新