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

标签 angularjs jasmine karma-runner

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

关于angularjs - 模拟$ httpBackend-如何处理 “Unexpected request, No more request expected”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22405085/

相关文章:

javascript - 如何在 AngularJS 单元测试中 stub `$window.localStorage`?

使用 "controller as"语法的 AngularJS Controller 单元测试

javascript - 在函数内设置全局范围变量

javascript - 通过 url 将参数从 Angular $http.get 传递到 django views.py

javascript - Angularjs 中字母数字的正则表达式

javascript - Jasmine 测试随机失败

unit-testing - 模拟 router.events.subscribe() Angular2

unit-testing - Karma 没有运行测试

angularjs - angular karma runner 无限期挂起

javascript - Datepicker 不更新 ng-model