繁体   English   中英

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

[英]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.

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