如何使用http get为角度服务编写Jasmine测试?

时间:2017-05-14 08:27:46

标签: angularjs http jasmine

我已经阅读了几篇帖子,但仍无法为我找出解决方案。我有一个Angular服务

App.factory('PoolService', ['$http', '$q', function($http, $q){
    return {
        fetchAllPools: 
            function() {
                return $http.get('http://localhost:5555/demo/pools/').then( ...

使用服务的Angular控制器

App.controller('PoolController', ['$scope', 'PoolService', function($scope, PoolService) {
          var self = this;
          self.pool={id:null,name:'', description:''};
          self.pools=[]; ...

现在我正在尝试为控制器编写一个Jasmine单元测试,看起来像:

describe('pool', function () {
    beforeEach(module('myApp'));

    var $controller;

    beforeEach(inject(function(_$controller_){
        $controller = _$controller_;
    }));

    describe('pool list', function () {

        it('after fetching pools the pool list should contain elements', function () {
            var $scope = {};
            var controller = $controller('PoolController', { $scope: $scope});

            controller.fetchAllPools();

            expect($scope.pools).toBeDefined();
        });
    });
});

fetchAllPools()

的实现
fetchAllPools: 
    function() {
        return $http.get('http://localhost:5555/demo/pools/').then(
                function(response){
                    return response.data;
                }, 
                function(errResponse){
                    console.error('Error while fetching pools');
                    return $q.reject(errResponse);
                }
            );
        },

我的问题是服务没有执行http.get请求 - 它只是等待无休止。

有人可以帮忙吗?我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

在控制器测试中模拟服务:

it('after fetching pools the pool list should contain elements', inject(function(PoolService, $q, $rootScope) {
  var $scope = $rootScope.$new();
  spyOn(PoolService, 'fetchAllPools').and.returnValue($q.when([]));
  var controller = $controller('PoolController', { $scope: $scope });

  controller.fetchAllPools();
  $scope.$apply();

  expect($scope.pools).toBeDefined();
});