对使用$ http的控制器进行单元测试

Ric*_*d V 7 unit-testing mocking jasmine angularjs

我有一个简单的控制器,我需要它做的第一件事是为范围分配一个值.

function TestCtrl($scope, $http) {
    $scope.listForms = 'some list';
}
Run Code Online (Sandbox Code Playgroud)

控制器的以下测试按预期工作:

describe('Testing a controller', function() {

    var ctrl, scope, httpMock;

    beforeEach(inject(function($injector) {
        scope = $injector.get('$rootScope').$new();
        ctrl = $injector.get('$controller');
        ctrl(TestCtrl, { $scope: scope });
    }));

    it("assigns to scope", function() {
      expect(scope.listForms).toMatch("some list");
    });
});
Run Code Online (Sandbox Code Playgroud)

但是当我更改函数以从我的API获取列表时

function TestCtrl($scope, $http) {
  $http.get('/api/listForms').success(function(list) {
    $scope.aListOfForms = 'some list';
  });
}
Run Code Online (Sandbox Code Playgroud)

并且测试变为

describe('Testing a controller', function() {

    var ctrl, scope, httpMock;

    beforeEach(inject(function($injector) {
        httpMock = $injector.get('$httpBackend');

        scope = $injector.get('$rootScope').$new();
        httpMock.when('GET', '/tactical/api/listOrderForms').respond("an order form");

        ctrl = $injector.get('$controller');
        ctrl(TestCtrl, {
            $scope: scope,
            $http: httpMock
        });
    }));

    it("gets the list from the api and assigns it to scope", function() {
      httpMock.expectGET('tactical/api/listOrderForms');
      expect(scope.orderFormList).toMatch("an order form");
      httpMock.flush();
    });
});
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

TypeError: 'undefined' is not a function
Expected undefined to match 'an order form'.
Error: No pending request to flush !
Run Code Online (Sandbox Code Playgroud)

有谁知道我做错了什么?提前致谢.

Ken*_*nne 8

$ http用于$httpBackend与外部资源交谈.你已经嘲笑了$httpBackend,但是控制器仍然需要$http通过接口与它交谈.

这应该这样做:

describe('Testing a controller', function() {

    var ctrl, scope, httpMock;

    beforeEach(inject(function($controller, $rootScope, $httpBackend) {
        httpMock = $httpBackend;

        scope = $rootScope.$new();
        httpMock.when('GET', '/tactical/api/listOrderForms').respond("an order form");

        ctrl = $controller;
        ctrl(TestCtrl, {
            $scope: scope
        });
    }));

    it("gets the list from the api and assigns it to scope", function() {
      httpMock.expectGET('tactical/api/listOrderForms');
      httpMock.flush();
      expect(scope.orderFormList).toMatch("an order form");
    });
});
Run Code Online (Sandbox Code Playgroud)