AngularJS - Unit test for http get to JSON file

纵饮孤独 提交于 2019-12-13 04:13:07

问题


I am trying to write a unit test to test a simple factory that performs a http.get to retrieve a JSON file.

The factory is called within my controller.

Here's a plunker showing my http.get: http://plnkr.co/edit/xg9T5H1Kreo4lwxzRQem?p=preview

Ctrl:

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

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

});

Factory:

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');
      });
    }
  }
});

Test:

// ---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();
            });

    })
});

Error:

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

回答1:


You should assign $httpBackend to httpMock in beforeEach like this:

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


来源:https://stackoverflow.com/questions/27057522/angularjs-unit-test-for-http-get-to-json-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!