一尘不染

使用$ httpBackend对AngularJS控制器进行单元测试

angularjs

对于我一生,我无法让$ httpBackend在执行$ http get请求的控制器上工作。我已经尝试了几个小时=)

我将其简化为下面可以最简单的形式。如果我通过测试

  • 在控制器中注释掉$ http.get()请求
  • 在测试中注释掉“ httpMock.flush()”
  • 并更改“猪”和“狗”以匹配

也就是说,这是一个有效的工作测试和应用程序。

如果放回去,则会在底部显示错误。


app / js / app.js

// Declare a module which depends on filters and services.
var myApp = angular
  .module('myApp', ['ngRoute', 'myApp.filters', 'myApp.services',
                              'myApp.directives'])
  .config(['$routeProvider' , function($routeProvider) {

    $routeProvider
      .when("/dashboard", {
        templateUrl: "partials/dashboard.html",
        controller: cDashboard
      })

      .otherwise({redirectTo: "/dashboard"});
  }]);

// Pre-define our main namespace modules.
angular.module('myApp.directives' , []);
angular.module('myApp.filters'    , []);
angular.module('myApp.services'   , []);
angular.module('myApp.controllers', []);

app / js / controller.js

function cDashboard ($scope, $http) {
  $scope.data = "dog";

  // Fetch the actual data.
  $http.get("/data")
    .success(function (data) { $scope.data = data })
    .error(function () {});
}

cDashboard.$inject = [ '$scope', '$http' ];

测试/单位/控制器Spec.js

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

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

    httpMock = $httpBackend;
    httpMock.when("GET", "/data").respond("pig");
  }));

  it("should get 'pig' from '/data'", function () {
    httpMock.expectGET("/data").respond("pig");
    expect(scope.data).toBe("pig");
  });

});

这是我在shell中得到的错误:

INFO [watcher]: Changed file "/home/myApp/test/unit/controller/cDashboard.js".
Chrome 26.0 (Linux) cDashboard should get 'pig' from '/data' FAILED
    Error: No pending request to flush !
        at Error (<anonymous>)
        at Function.$httpBackend.flush (/home/myApp/test/lib/angular/angular-mocks.js:1171:34)
        at null.<anonymous> (/home/myApp/test/unit/controller/cDashboard.js:15:18)
Chrome 26.0 (Linux): Executed 1 of 1 (1 FAILED) (0.326 secs / 0.008 secs)

阅读 176

收藏
2020-07-04

共1个答案

一尘不染

测试代码中有几个问题:

  1. 所述控制器被创建 之前httpMock被构造成与响应pig。该expectGet调用应在实例化控制器之前发生。
  2. httpMock需要刷新请求
  3. httMock.when,只要你有没有必要expectGet

工作示例:http :
//plnkr.co/edit/lUkDMrsy1KJNai3ndtng?p=preview

describe('cDashboard', function(){
  var scope, controllerService, httpMock;

  beforeEach(inject(function ($rootScope, $controller, $httpBackend) {
    scope = $rootScope.$new();
    controllerService = $controller;
    httpMock = $httpBackend;
  }));

  it("should get 'pig' from '/data'", function () {
    httpMock.expectGET("/data").respond("pig");
    ctrl = controllerService('cDashboard', {$scope: scope});
    httpMock.flush();
    expect(scope.data).toBe("pig");
  });
});
2020-07-04