AngularJS - http获取JSON文件的单元测试

时间:2014-11-21 09:00:57

标签: angularjs unit-testing angularjs-scope jasmine karma-jasmine

我正在尝试编写单元测试来测试执行factory以检索JSON文件的简单http.get

在我的控制器内调用工厂。

这是一个显示我的http.get:http://plnkr.co/edit/xg9T5H1Kreo4lwxzRQem?p=preview

的傻瓜

控制:

app.controller('MainCtrl', function($scope, $http, factoryGetJSONFile) { 

  factoryGetJSONFile.getMyData(function(data) {
    $scope.Addresses = data.Addresses.AddressList;
    $scope.People = data.Names.People;
  });

});

厂:

app.factory('factoryGetJSONFile', function($http) {
  return {
    getMyData: function(done) {
      $http.get('data.json')
      .success(function(data) {
        done(data);
      })
      .error(function(error) {
        alert('An error occured whilst trying to retrieve your data');
      });
    }
  }
});

测试:

// ---SPECS-------------------------

describe('with httpBackend', function () {
    var app;
    beforeEach(function () {
        app = angular.mock.module('plunker')
    });

    describe('MyCtrl', function () {
        var scope, ctrl, theService, httpMock;

        beforeEach(inject(function ($controller, $rootScope, factoryGetJSONFile, $httpBackend) {
            scope = $rootScope.$new(),
            ctrl = $controller('MyCtrl', {
                $scope: scope,
                factoryGetJSONFile: theService,
                $httpBackend: httpMock
            });
        }));

        it("should make a GET call to data.json", function () {
                console.log("********** SERVICE ***********");
                  httpMock.expectGET("data.json").respond("Response found!");
                //expect(factoryGetJSONFile.getMyData()).toBeDefined();
                httpMock.flush();
            });

    })
});

错误:

TypeError: 'undefined' is not an object (evaluating 'httpMock.expectGET')

1 个答案:

答案 0 :(得分:2)

您应该将$httpBackend分配到httpMock beforeEach,如下所示:

   beforeEach(inject(function ($controller, $rootScope, factoryGetJSONFile, $httpBackend) {
        httpMock = $httpBackend;
        scope = $rootScope.$new();
        ctrl = $controller('MyCtrl', {
            $scope: scope,
            factoryGetJSONFile: factoryGetJSONFile,
            $httpBackend: httpMock
        });
    }));