【问题标题】:AngularJS - Unit test for http get to JSON fileAngularJS - http 获取 JSON 文件的单元测试
【发布时间】:2014-11-21 09:00:57
【问题描述】:

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

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

这是一个显示我的 http.get 的 plunker: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;
  });

});

工厂:

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

【问题讨论】:

  • 你在哪里定义 theService 对象?
  • 您的代码现在只有在您编写 factoryGetJSONFile: factoryGetJSONFile 时才会编译,但它只会调用原始服务。您必须定义一个模拟服务并将其放入服务中

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


【解决方案1】:

您应该像这样在beforeEach 中将$httpBackend 分配给httpMock

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

【讨论】:

  • 为什么要在 beforeEach 和 ctrl 参数里面定义呢?
  • 试过你的代码,得到一个错误:错误:意外请求:GET /data.json?预期 GET /data.json 在哪里?来自??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-30
  • 1970-01-01
  • 1970-01-01
  • 2017-11-03
  • 2013-05-27
  • 2023-01-21
  • 1970-01-01
相关资源
最近更新 更多