使用 Jasmine/Karma 单元测试 AngularJS $http 事件处理程序?
Unit testing AngularJS $http event handler with Jasmine/Karma?
我正在使用 AngularJS 1.5.8,并且我有一个工厂,其方法是 returns $http 请求的一个实例。它包括一个进度eventHandler
。我的问题是,如何使用 Jasmine/Karma 测试此事件处理程序?通常,请求是通过 $httpBackend.expectPOST
或类似的方式模拟它们来测试的,但是 progress 事件永远不会被触发。如果我不模拟它,业力会抱怨一个意外的请求。我该怎么做?
我明白了。这样做的方法是使用 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]);
在 beforeEach(...)
回调中的 module(...)
定义中设置后,现在我可以在我的单元测试中引用 $httpBackend.eventHandlers
并获得对所有这些的引用:)
我正在使用 AngularJS 1.5.8,并且我有一个工厂,其方法是 returns $http 请求的一个实例。它包括一个进度eventHandler
。我的问题是,如何使用 Jasmine/Karma 测试此事件处理程序?通常,请求是通过 $httpBackend.expectPOST
或类似的方式模拟它们来测试的,但是 progress 事件永远不会被触发。如果我不模拟它,业力会抱怨一个意外的请求。我该怎么做?
我明白了。这样做的方法是使用 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]);
在 beforeEach(...)
回调中的 module(...)
定义中设置后,现在我可以在我的单元测试中引用 $httpBackend.eventHandlers
并获得对所有这些的引用:)