在 Jasmine 测试中模拟 AngularJS $httpBackend 并使用装饰器时出现“$httpBackend.when 不是函数”错误
"$httpBackend.when is not a function" error when mocking AngularJS $httpBackend in Jasmine tests and using a decorator
我正在为 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 不是一个函数”。
知道如何解决这个问题吗?我更喜欢在我的应用程序配置中没有测试特定代码的解决方案。
您可以简单地在特定模块中定义装饰器,而不要在您的测试中加载该模块。
除了装饰 httpBackend,您还可以使用 http 拦截器。在你的测试中加载它会导致同样的问题(但如果你愿意,你仍然可以使用相同的技术来避免在测试中加载它)。
我正在为 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 不是一个函数”。
知道如何解决这个问题吗?我更喜欢在我的应用程序配置中没有测试特定代码的解决方案。
您可以简单地在特定模块中定义装饰器,而不要在您的测试中加载该模块。
除了装饰 httpBackend,您还可以使用 http 拦截器。在你的测试中加载它会导致同样的问题(但如果你愿意,你仍然可以使用相同的技术来避免在测试中加载它)。