[英]Jasmine unit test in AngularJs for http method
我編輯了問題以添加錯誤:
這是我使用http服務的控制器方法:
$scope.getWeatherInfo = function(){
$http.get($scope.url).then(function (response) {
$scope.city = response.data.name;
});
}
而我的測試:
describe('controller', function() {
beforeEach(module('testApp'));
var $controller;
var $httpBackend;
beforeEach(inject(function(_$controller_,_$httpBackend_){
$controller = _$controller_;
$httpBackend = _$httpBackend_;
}));
describe('$scope.test ', function() {
it('http get the resource from the API and construct the weatherInfo object', function() {
var $scope = {};
var controller = $controller('controller', { $scope: $scope });
$scope.url = 'http://api.openweathermap.org/data/2.5/weather?q=Sydney&appid=0d00180d180f48b832ffe7d9179d40c4';
$scope.getWeatherInfo()
$httpBackend.when('GET', 'http://api.openweathermap.org/data/2.5/weather?q=Sydney&appid=0d00180d180f48b832ffe7d9179d40c4').respond(200, { data:{name:'sydney'}});
$httpBackend.flush()
expect($scope.city).toEqual('sydney);
});
});
});
我得到了這個Expected undefined to equal 'sydney' error
。 這可能是由於函數的偶然性所致,但是我在這里缺少什么呢?
角度承諾僅在摘要循環中解決。 您需要在示波器上觸發摘要循環。 為此,您需要將真實作用域傳遞給控制器,然后在其上調用摘要(或根作用域)。
首先注入$rootScope
服務。
var $controller;
var $httpBackend;
var $rootScope;
beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_) {
$controller = _$controller_;
$httpBackend = _$httpBackend_;
$rootScope = _$rootScope_;
}));
然后在執行您的期望之前調用$digest()
。
it('http get the resource from the API and construct the weatherInfo object', function () {
var $scope = $rootScope.$new();
var controller = $controller('controller', { $scope: $scope });
$scope.url = 'http://api.openweathermap.org/data/2.5/weather?q=Sydney&appid=0d00180d180f48b832ffe7d9179d40c4';
$scope.getWeatherInfo();
$httpBackend.when('GET', 'http://api.openweathermap.org/data/2.5/weather?q=Sydney&appid=0d00180d180f48b832ffe7d9179d40c4').respond(200, { data: { name: 'sydney' } });
$httpBackend.flush();
$scope.$digest(); // or $rootScope.$digest();
expect($scope.city).toEqual('sydney');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.