模拟 $httpBackend - 如何处理“意外的请求,没有更多的请求"? [英] Mocking $httpBackend - how to handle "Unexpected request, No more request expected"?
问题描述
我有一个 Jasmine 测试,编码如下:
I have a Jasmine test that is coded like this:
it ("should send correct message to server to get data, and correctly set up scope when receiving it", function(){
$httpBackend.when('GET', 'https://localhost:44300/api/projectconfiguration/12').respond(fakedDtoBase);
$routeParams.projectId=fakeId; // user asks for editing project
scope.$apply(function(){
var controller=controllerToTest(); // so controller gets data when it is created
});
expect(scope.projectData).toEqual(fakedDtoBase);
});
它有点工作,但我收到错误:
and it kind of works, but I get the error:
Error: Unexpected request: GET views/core/main/main.html
No more request expected
at $httpBackend (C:/SVN/src/ClientApp/client/bower_components/angular-mocks/angular-mocks.js:1207:9)
at sendReq (C:/SVN/src/ClientApp/client/bower_components/angular/angular.js:7800:9)
at $http.serverRequest (C:/SVN/src/ClientApp/client/bower_components/angular/angular.js:7534:16)
(more stack trace)....
我确实意识到我可以模拟所有其他调用.但是假设我不在乎我的测试还想加载什么,因为它可能会调用其他一些东西.我如何确保所有其他请求都默默地发生",也许为其他所有请求提供一个虚拟响应?
I do realise that I can mock every other call. But let's say I do not care what else my test wants to load as it may call few other things. How I can make sure that every other requests just "happen silently", maybe offering a single dummy response for everything else?
推荐答案
您的测试失败,因为发出了您未指定的请求.
Your test fails because a request is made which you haven't specified.
尝试添加:
$httpBackend.when('GET', 'views/core/main/main.html').respond(fakedMainResponse);
当然你也应该定义fakedMainResponse
.
另请查看文档(请求期望与后端定义部分),其中说:
Please take a look also at the documentation (section Request Expectations vs Backend Definitions) which says:
请求期望提供了一种对请求进行断言的方法由应用程序生成并定义对这些请求的响应.如果没有提出预期的请求或者它们是顺序错误.
Request expectations provide a way to make assertions about requests made by the application and to define responses for those requests. The test will fail if the expected requests are not made or they are made in the wrong order.
$httpBackend.when
的第二个参数实际上是一个 RegExp
.因此,如果您提供一个 RegExp
将匹配所有其他请求,它应该可以工作.
The second paramete of $httpBackend.when
is actually a RegExp
. So if you provide a RegExp
that will match all other requests it should work.
这篇关于模拟 $httpBackend - 如何处理“意外的请求,没有更多的请求"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!