多个连续的httpBackend请求会导致意外的请求

Chr*_*erJ 5 angular-resource httpbackend

我正在测试轮询资源的序列,直到满足条件.

Book = $resource("/books/:id", {id: "@id"});

function poll(success) {
  Book.get({id:1}, function() {
    if (canStop) {
       success();
    } else {
       $timeout(poll, 1000);
    }

  });
};
Run Code Online (Sandbox Code Playgroud)

以下测试失败了 Error: Unsatisfied requests: GET /user_workshops/1

describe('poll', function() {
  beforeEach(function() {
    $httpBackend.expectGET('/books/1').respond(200,{id:1});
    $httpBackend.expectGET('/books/1').respond(200,{id:1, newVal:1});

    poll(function() {
       successCalled = true;
    });

    $httpBackend.flush();
    $timeout.flush();

    canStop=true;

    $httpBackend.flush();
  });

  it('should call success when canStop is true', function() {
     expect(successCalled).toBe(true);
  });
});
Run Code Online (Sandbox Code Playgroud)

我已经尝试重新排列测试顺序,将第二个放在第二个expectGET之前,httpBackend.flush()但后来我得到:

Error: Unexpected request: POST /books/1
No more request expected
Run Code Online (Sandbox Code Playgroud)

Chr*_*erJ 10

经过一个小时的拔毛后,我意识到httpBackend 对于测试被调用的顺序非常具体 - 期望必须不是在调用flush之前设置,而是在创建资源请求之前设置,并且当你调用flush时必须已经完全,只有预期的要求.

这意味着如果要在顺序请求之间进行刷新,请求和期望的顺序必须完全符合:

$httpBackend.expectGET('...')
resource.get();
$httpBackend.flush()
$httpBackend.expectGET('...')
resource.get();
$httpBackend.flush()
...
etc
Run Code Online (Sandbox Code Playgroud)

因此,对于上面的代码,如果我将排序更改为:

describe('poll', function() {
  beforeEach(function() {
    $httpBackend.expectGET('/books/1').respond(200,{id:1});

    poll(function() {
       successCalled = true;
    });

    $httpBackend.flush();

    $httpBackend.expectGET('/books/1').respond(200,{id:1, newVal:1});

    $timeout.flush();
    canStop=true;

    $httpBackend.flush();
  });

  it('should call success when canStop is true', function() {
     expect(successCalled).toBe(true);
  });
});
Run Code Online (Sandbox Code Playgroud)