简体   繁体   中英

Jasmine unit test in AngularJs for http method

I edited the questions to add the errors:

This is my controller method that use http service:

  $scope.getWeatherInfo = function(){
        $http.get($scope.url).then(function (response) {
        $scope.city  = response.data.name;          
        });
      }

And my test:

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);
});
});
});

I got this Expected undefined to equal 'sydney' error . It is probably due to the ascynchrous nature of the function, but what am I missing here?

Angular promises are only resolved in a digest cycle. You'll need to trigger a digest cycle on the scope. To do this you'll need to pass a real scope to your controller, then call digest on it (or the root scope).

First inject the $rootScope service.

var $controller;
var $httpBackend;
var $rootScope;
beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_) {
    $controller = _$controller_;
    $httpBackend = _$httpBackend_;
    $rootScope = _$rootScope_;
}));

Then call $digest() before performing your expectations.

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');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM