angularjs - 在 Jasmine 测试中模拟 AngularJS $httpBackend 并使用装饰器时出现 "$httpBackend.when is not a function"错误

标签 angularjs jasmine decorator angular-http angular-http-interceptors

我正在使用 Angular 服务 $httpBackend 的装饰器来更改所有 http 调用的 URL:

app.config(function($provide) {
   $provide.decorator('$httpBackend', function($delegate) {
      return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
          url = changeUrl(url);
          $delegate(method, url, post, callback, headers, timeout, withCredentials, responseType);
      };
   })
});

在一些 Jasmine 测试中,我需要模拟 $httpBackend 服务:

describe('...', function() {
    beforeEach(module('...'));
    beforeEach(inject(function($injector) {
        $httpBackend = $injector.get('$httpBackend');
        $httpBackend.when('GET', '...').respond(function(method, url) {
            return ...
        });
    }));
}

现在,在执行这些测试时,我收到错误“$httpBackend.when is not a function”。

知道如何解决这个问题吗?我更喜欢一个无需在应用程序配置中测试特定代码的解决方案。

最佳答案

您可以简单地在特定模块中定义装饰器,并且不在测试中加载该模块。

除了装饰 httpBackend,您还可以使用 http 拦截器。在测试中加载它会导致同样的问题(但如果您愿意,您仍然可以使用相同的技术来避免在测试中加载它)。

关于angularjs - 在 Jasmine 测试中模拟 AngularJS $httpBackend 并使用装饰器时出现 "$httpBackend.when is not a function"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33329090/

相关文章:

python - Python 中类装饰的实际用途是什么?

regex - 美国邮政编码和加拿大邮政编码的 Angular ng-pattern 正则表达式代码

javascript - 在渲染 Angularjs 之前隐藏元素

angularjs - Angular + Jasmine : beforeEach() syntax with module()

javascript - 为什么我的 Jasmine 测试在 DEFAULT_TIMEOUT_INTERVAL 之前超时?

go - Golang中如何装饰不同签名的函数?

javascript - 使用 angularJS 智能表

javascript - 如何在 AngularJS 中正确使用 ng-click?

javascript - Grunt、Jasmine、Phantom、React 单元测试 : React throws on ReactElementValidator

python - 在类中定义装饰器,在类定义中也可用