使用Jasmine / Karma对AngularJS $ http事件处理程序进行单元测试?

时间:2018-10-02 19:07:43

标签: angularjs unit-testing http karma-jasmine eventhandler

我正在使用AngularJS 1.5.8,并且我有一个工厂,该工厂的方法可返回$ http请求的实例。它包括进度eventHandler。我的问题是,如何使用Jasmine / Karma测试此事件处理程序?通常,通过$httpBackend.expectPOST或类似的方法对请求进行模拟来测试请求,但是进度事件永远不会触发。而且,如果我不嘲笑它,Karma会抱怨一个意外的请求。我该怎么做?

1 个答案:

答案 0 :(得分:0)

我知道了。做到这一点的方法是使用AngularJS装饰器扩展$ httpBackend,从而能够拦截对后端的调用,记录传递给它们的处理程序,并委派给原始对象:

    var httpDecorator = function($delegate) {
    $delegate.eventHandlers = [];
    var newBackend = function() {
      $delegate.eventHandlers.push(arguments[8]);
      return $delegate.apply(null, arguments);
    };
    angular.forEach($delegate, function(value, key) {
      if ($delegate.hasOwnProperty(key)) {
        newBackend[key] = value;
      }
    });
    return newBackend;
  };
  $provide.decorator('$httpBackend', ['$delegate', httpDecorator]);

通过在module(...)回调中的beforeEach(...)定义中进行设置,现在我可以在单元测试中引用$httpBackend.eventHandlers并获得所有引用:)