在Angular控制器中使用$ httpBackend进行测试,不返回模拟响应

时间:2015-02-05 16:41:10

标签: angularjs unit-testing karma-jasmine

我对Angular JS的测试很新,在单元测试控制器时遇到了一些问题(我正在使用Karma和Jasmine)。

我知道最佳实践是单独测试资源工厂和控制器,但是,现在,我正在尝试一次测试它们,因为我的控制器具有调用这些资源的函数。

  angular.module('myApp.controllers')
  .controller('myDocumentsController', ['documentResourceFactory', '$scope', function(documentResourceFactory, $scope) {  

    $scope.queryDocuments = function(){
      $scope.userDocuments = documentResourceFactory.query($scope.queryParams(), function(){
        $scope.fetchingDocuments=false
      })
    };

    $scope.queryParams = function() {
      if($scope.feedItem) {
        return { "feed_item_id": $scope.feedItem.id }  
      } else {
        return { "entry_id": $scope.entry.id }
      }
    };
}])

这是我正在为这个控制器构建的测试,我似乎无法开始工作:

describe('myDocumentsController', function(){
    var $scope, $httpBackend, $rootScope, $controller, documentResourceFactory;

beforeEach(angular.mock.module('myApp'));

beforeEach(angular.mock.inject(function(_$rootScope_, _$controller_, _$httpBackend_, _documentResourceFactory_){
    $rootScope = _$rootScope_;
    $scope = $rootScope.$new();
    $controller = _$controller_
    $httpBackend = _$httpBackend_;
    documentResourceFactory = _documentResourceFactory_
    $controller('myDocumentsController', {$scope: $scope});
}));


    describe('called when looking at feed item documents', function(){
    beforeEach(function(){
        $scope.feedItem = {
            "id": 3533669,
            "description": "Exhibit",
            "published_at": "2015-02-04T15:14:51.000Z",
            "published_at_to_i": 1423062891,
        };
    });

    //PASSING
    it('should be a feedItem on the scope', function(){
        expect($scope.feedItem).not.toBeNull();
    });

    //PASSING
    it('should have queryParams() returning "feed_item_id" when there is a feed item on the scope', function(){
        expect($scope.queryParams()).toEqual({"feed_item_id": 3533669});
    });


    // THIS TEST IS NOT PASSING
    it('should return a list of documents associated a feed item', function(){
        $httpBackend.when('GET', 'https://example.com/api/v1/my_documents?feed_item_id=3533669').respond([{}, {}]);

        $scope.$apply(function() {
            $scope.queryDocuments()
        });

        expect($scope.userDocuments.length).toEqual(2);
        $httpBackend.flush();
    }); 
});

这里的问题是,无论我做什么,$ httpBackend永远不会被击中;因此,永远不要回应两个空对象。当我测试它时,我得到一个空数组,它告诉我它“预期0到2等于”。所以似乎测试运行正常,我似乎无法从$ httpBackend获得响应。当我在开发服务器上运行它时,所有这些代码都运行良好。

我在这里做错了什么?提前谢谢!

0 个答案:

没有答案