每次 AngularJS 测试执行 rootScope.digest() 或 httpBackend.flush() 时如何避免“错误:意外请求:GET”

2024-02-26

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

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$/为什么不检查是否向correct端点?无论是指令部分还是 API 调用。

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

每次 AngularJS 测试执行 rootScope.digest() 或 httpBackend.flush() 时如何避免“错误:意外请求:GET” 的相关文章

随机推荐