Angular的httpBackend不支持waitsFor和run (expectpromise)

Angular httpBackend not working with waitsFor and run (expects promise)

本文关键字:run expectpromise waitsFor httpBackend 不支持 Angular      更新时间:2023-09-26

我新的单元测试角和有很多麻烦得到我的承诺和httpBackend的工作。我得到的错误是"等待某事发生后5000ms超时"。

这是我到目前为止的单元测试:

describe('querySingle', function () {
  var httpBackend;
  beforeEach(inject(function ($injector) {
    httpBackend = $injector.get('$httpBackend');
  }));
  it('should return the $http promise object when valid', function () {
    httpBackend.expectGet('/rest/report/current/1234123412341234').respond('Hi');
    var request = CurrentRequests.querySingle('1234123412341234');
    var a;
    request.then(function (data) {
      a = data;
    });
    waitsFor(function () {
      return a;
    });
    runs(function () {
      expect(a).toBe('Hi');
    });
  });
  afterEach(function() {
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
  });
});

任何建议或帮助是感激的,我认为我的语法是错误的地方,但angular文档在这方面没有帮助。

实际上,我发现Angular文档非常有帮助,清晰和详细!

waitsFor用于当数据确实从服务器获取时。但是Angular的模拟$httpBackend提供了flush()方法来帮助异步行为的同步测试。

所以,你的测试应该看起来像这样:
...
it('should return the $http promise object when valid', function () {
    httpBackend.expectGet('/rest/report/current/1234123412341234').respond('Hi');
    var request = CurrentRequests.querySingle('1234123412341234');
    var a;
    request.then(function (data) {
        a = data;
    });
    httpBackend.flush();
    expect(a).toBe('Hi');
});
...