我正在使用 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/