Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

angularjs - Mocking $httpBackend - how to handle "Unexpected request, No more request expected"?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your test fails because a request is made which you haven't specified.

Try to add:

$httpBackend.when('GET', 'views/core/main/main.html').respond(fakedMainResponse);

Of course you should also define 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...