angularjs - 每次 AngularJS 测试执行 rootScope.digest() 或 httpBackend.flush() 时如何避免 'Error: Unexpected request: GET'

标签 angularjs unit-testing

我所有的单元测试,而不是 E2E 测试,执行显式 rootScope.digest() 或 httpBackend.flush() 以刷新异步回调,遇到错误:

How to avoid the 'Error: Unexpected request: GET'
No more request expected

我估计是因为httpBackend调用了ui-router模板。我不知道它为什么要这样做。我不是要这个。我只希望它调用我的模拟 json 服务。

这个错误迫使我在每个 it() 块中有以下语句:
$httpBackend.whenGET(/\.html$/).respond('');  

必须有更整洁的方法。

特别是如果测试首先没有使用 $httpBackend :
  it('should return the list of searched users', function() {
    // Always use this statement so as to avoid the error from the $http service making a request to the application main page
    $httpBackend.whenGET(/\.html$/).respond('');

    var users = null;
    UserService.search('TOTO', 1, 10, 'asc', function(data) {
      users = data.content;
    });
    $rootScope.$digest();
    expect(users).toEqual(RESTService.allUsers.content);
  });

测试通过了,但看起来很黑。或菜鸟:-)

编辑:另一个测试:
  it('should return the list of users', function () {
    // Always use this statement so as to avoid the error from the $http service making a request to the application main page
    $httpBackend.whenGET(/\.html$/).respond('');
    // Create a mock request and response
    $httpBackend.expectGET(ENV.NITRO_PROJECT_REST_URL + '/users/1').respond(mockedUser);
    // Exercise the service
    var user = null;
    RESTService.User.get({userId: 1}).$promise.then(function(data) {
      user = data;
    });
    // Synchronise
    $httpBackend.flush();
    // Check for the callback data
    expect(user.firstname).toEqual(mockedUser.firstname);
    expect(user.lastname).toEqual(mockedUser.lastname);
  });

最佳答案

这显然是设计使然,您的测试应该检查是否正在进行 HTTP 调用以及它们是否正在请求正确的 URL。而不是检查是否向 /\.html$/ 发出请求为什么不检查是否向 发出请求?正确 端点?无论是指令部分还是 API 调用。

如果你坚持扔掉可能有用的测试,你可以移动你的 whenGET()beforeEach() .

关于angularjs - 每次 AngularJS 测试执行 rootScope.digest() 或 httpBackend.flush() 时如何避免 'Error: Unexpected request: GET',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29634780/

相关文章:

python - 格式化 python 单元测试的测试失败

Perl 单元测试模拟

javascript - AngularJS 工厂 $rootScope.$on 清理

javascript - ng-click 在 ng-repeat 中执行多次

javascript - 温泉 - 对话框中的按钮不起作用

java - JMockit 与 null 匹配

javascript - AngularJs 在 IE 上非常慢

android - 使用 ionic 在屏幕上显示手机的地理位置

unit-testing - 单元测试对象转换器

Python unittest 返回 "Ran 0 tests in 0.000s",我不知道为什么