【问题标题】:How to avoid the 'Error: Unexpected request: GET' every time an AngularJS test does a rootScope.digest() or httpBackend.flush()每次 AngularJS 测试执行 rootScope.digest() 或 httpBackend.flush() 时如何避免“错误:意外请求:GET”
【发布时间】:2015-04-14 18:26:18
【问题描述】:

我所有的 UNIT 测试,而不是 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);
  });

测试通过了,但它看起来很老套。或者是noobish :-)

编辑:另一个测试:

  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。为什么不实际 expect 调用您的用户 API 端点?
  • 是的,它确实发出了一个 http 请求。但是我的很多测试也是如此。我没明白你的问题。我将编辑问题以添加另一个展示相同解决方法的测试。

标签: angularjs unit-testing


【解决方案1】:

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

如果您坚持放弃可能有用的测试,您可以将您的 whenGET() 移至 beforeEach()

【讨论】:

  • 我正在阅读docs.angularjs.org/api/ngMock/service/$httpBackend 的文档,但仍然想知道whenGET 和expectGET 之间有什么区别。我了解 expectGET 是定义模拟请求。 whenGET 做同样的工作吗?
  • 这两个函数是用来模拟还是用来检查的?
  • 我的服务不应该首先调用任何 html 资源。它只是调用一个 json 端点。我不知道我该怎么做才能不扔掉这个东西并使测试更有用。
猜你喜欢
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-28
  • 2012-12-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多