在测试中,Angular mock 的 httpBackend 是如何隐式传递给$controller服务的?



此规范通过看起来应该失败。(该代码来自有关角和铁轨的书)

这是Angular App:

var app = angular.module('customers',[]);
app.controller("CustomerSearchController",
  ["$scope", "$http", function($scope, $http) {
    var page = 0;
    $scope.customers = [];
    $scope.search = function (searchTerm) {
      if (searchTerm.length < 3) {
        return;
      }
      $http.get("/customers.json",
        { "params": { "keywords": searchTerm, "page": page } }
      ).then(function(response) {
          $scope.customers = response.data;
        },function(response) {
          alert("There was a problem: " + response.status);
        }
      );
    };
  }
]);

,这是茉莉花规范:

describe("Error Handling", function () {
  var scope = null,
    controller = null,
    httpBackend = null;
  beforeEach(module("customers"));
  beforeEach(inject(function ($controller, $rootScope, $httpBackend) {
    scope = $rootScope.$new();
    httpBackend = $httpBackend;
    controller = $controller("CustomerSearchController", {
      $scope: scope
    });
  }));
  beforeEach(function () {
    httpBackend.when('GET', '/customers.json?keywords=bob&page=0').respond(500, 'Internal Server Error');
    spyOn(window, "alert");
  });
  it("alerts the user on an error", function() {
    scope.search("bob");
    httpBackend.flush();
    expect(scope.customers).toEqualData([]);
    expect(window.alert).toHaveBeenCalledWith(
      "There was a problem: 500");
    });
});

我不了解控制器如何访问$ httpbackend服务,并注入了传递的匿名函数,以注入以前的方法中。$示波器服务已通过,但httpbackend却没有。

$controller不取决于 $httpBackend服务, $httpBackend未传递给它。

$http取决于$httpBackend(因此名称)。$httpBackend在NGMOCK中被模拟实施中被覆盖,并由$http而不是原始$httpBackend使用(这不打算直接使用)。

在您的代码中:

app.controller(" customersearchcontroller",  [" $ scope"," $ http",功能($ scope,$ http){     ...   ]])

您正在要求Angular注入该文件中的$ HTTP。您在这里没有提供本地覆盖

controller = $ controler(" customereaghearchcontroller",{      $范围:范围    });

A Angular用它的内容满足了您的注射请求。正如@estus所说,ngmock中提供的覆盖物本身都注入了$ httpbackend,您在测试中已配置为以某种方式行动。

相关内容

最新更新