简体   繁体   English

AngularJs中针对Jasmine方法的Jasmine单元测试

[英]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: 这是我使用http服务的控制器方法:

  $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 . 我得到了这个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. 首先注入$rootScope服务。

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. 然后在执行您的期望之前调用$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.

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