Skip to main content
 首页 » 编程设计

angularjs之模拟$ httpBackend-如何处理 “Unexpected request, No more request expected”

2024年09月03日18jpfss

我有一个 Jasmine 测试,其编码如下:

  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); 
}); 

确实可行,但出现错误:
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).... 

我确实意识到我可以 mock 其他所有电话。但是,可以说我不在乎我的测试还要加载什么,因为它可能会调用其他一些东西。
我如何确保其他所有请求只是“默默发生”,也许对其他所有请求都提供了一个虚拟响应?

请您参考如下方法:

测试失败,因为发出了您未指定的请求。

尝试添加:

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

当然,您还应该定义 fakedMainResponse

请同时查看 documentation(“请求期望与后端定义”部分),其中:

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将与所有其他请求匹配,则它应该可以工作。