ale*_*cxe 7 javascript http http-head angularjs angularjs-http
在我们的内部angularjs项目中,其中一个服务有$http.head()
我正在尝试测试的调用.
为了测试,我正在使用由提供的Fake HTTP后端angular-mocks
.这是相关代码:
it('handle status code 200', inject(function ($httpBackend, ConnectionService) {
spyOn(Math, 'random').andReturn(0.1234);
httpBackend = $httpBackend;
httpBackend.expectHEAD('ping?rand=1234').respond(200);
ConnectionService.sendRequest();
httpBackend.flush();
expect(ConnectionService.stats.packetsReceived).toEqual(5);
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
}));
Run Code Online (Sandbox Code Playgroud)
将测试结果运行到以下错误中:
PhantomJS 1.9.7 (Mac OS X) connection service tests sendRequest function handle status code 200
FAILED TypeError: 'undefined' is not a function (evaluating 'httpBackend.expectHEAD('ping?rand=1234')')
at /path/to/app/app-connection-service_test.js:66
at d (/path/to/app/bower_components/angular/angular.min.js:35)
at workFn (/path/to/app/bower_components/angular-mocks/angular-mocks.js:2159)
Run Code Online (Sandbox Code Playgroud)
经过一番挖掘后,我发现了相关的github问题:
据我所知,这意味着expectHEAD()
在角度模拟中确实没有方法 - 它已被记录,但实际上,它还不是稳定角度释放的一部分.
什么是最好的方法?
请注意,我必须保持angular <= 1.2,因为此应用程序需要在IE8上运行(Angular 1.3正在放弃对IE8的支持).
我正在考虑的一个解决方法是替换head()
为get()
.在这种情况下,我可以用现有expectGET()
方法测试它.但我不确定这些缺点.
您可以自己添加更改:https://github.com/revolunet/angular.js/commit/b2955dd52725241dd9519baa12fe8ca74659004b
这是1523行的angular-mocks.js中的一行更改:
1523: - angular.forEach(['GET', 'DELETE', 'JSONP'], function(method) {
1523: + angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) {
Run Code Online (Sandbox Code Playgroud)
看到你必须继续使用非当前版本的Angular,它不会在将来引起太多问题.
编辑:回顾JoelJeske的回答,他提出了一个很好的观点 - 你可以轻松地做到这一点而不用分叉.我将对他的解决方案做出的一个改变是,而不是直接调用该方法
$httpBackend.expect('HEAD', 'ping?rand=1234').respond(200);
Run Code Online (Sandbox Code Playgroud)
我会直接创建快捷方法:
$httpBackend.expectHEAD = function(url, headers) {
return $httpBackend.expect('HEAD', url, undefined, headers);
};
Run Code Online (Sandbox Code Playgroud)
然后你可以这样做:
$httpBackend.expectHEAD('ping?rand=1234').respond(200);
Run Code Online (Sandbox Code Playgroud)
与分叉和编辑库相反,使用底层方法会是更好的做法。
$httpBackend.expect('HEAD', 'ping?rand=1234').respond(200);
Run Code Online (Sandbox Code Playgroud)
您不能使用的另一种方法只是快捷方法。使用这种方法比更改库更好、更容易。
归档时间: |
|
查看次数: |
253 次 |
最近记录: |