【发布时间】:2018-02-09 21:26:45
【问题描述】:
我跟随 this tutorial 对返回 aPromise 但无法正常工作的服务进行单元测试。
我的服务返回一个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 错误。
【问题讨论】:
标签: javascript angularjs unit-testing promise jasmine