gpt4 book ai didi

javascript - Angular 单元测试服务返回 Promise Jasmine

转载 作者:行者123 更新时间:2023-12-03 02:31:47 25 4
gpt4 key购买 nike

我关注了this tutorial对返回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
};
});

我的 Controller 有一个函数可以解析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没有期望getGeo应该返回一个 promise 。似乎模拟服务内的代码永远不会被调用。但是如果我移出 expect($scope.weatherInfo.url).not.toBeNull() 并将其放在 $scope.$digest() 下,我会得到无法读取未定义的属性“url” 错误。

最佳答案

  1. var position = {coords:{coords:{latitude:'1',latitude:'3'}}};
    $getGeo().then(函数(位置) {
    期望($scope.weatherInfo.url).not.toBeNull();
    }

回调中的变量 - 它是 Promise 将返回的数据。这不是您的 varposition = {coords:{coords:{latitude:'1',latitude:'3'}}};

  • 我认为你不应该在测试中调用工厂。当您第一次注入(inject)工厂时,工厂只会调用构造函数一次。所以你只需要下一步

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

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

    spyOn(navigator.geolocation, 'getCurrentPosition').andReturn(/* 这里是您期望的数据 */)

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

    关于javascript - Angular 单元测试服务返回 Promise Jasmine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48705569/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com