AngularJS - http get to JSON 文件的单元测试



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

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

这是一个显示我的http.get的plunker: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')
您应该像

这样将$httpBackend分配给beforeEach httpMock

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

相关内容

  • 没有找到相关文章

最新更新