Angularjs单元测试和httpbackend超时

时间:2016-03-11 13:53:14

标签: javascript angularjs unit-testing

我在测试世界中并不陌生,因为我使用mocha sinon chai和nodejs在TDD中多次工作。

我对Angularjs测试及其工作方式感到有些不安。

实际上,我需要测试一下我能做的最简单的方法:

/** @test {HateoasService#loadRessource}*/
describe('HateoasService', function() {

  let service = null;
  let remoteBackend = null;
  beforeEach(angular.mock.module('app'));

  beforeEach(inject((HateoasService, $httpBackend) => {
    remoteBackend = $httpBackend;
    service = HateoasService;
  }));

  afterEach(function() {
    remoteBackend.verifyNoOutstandingExpectation();
    remoteBackend.verifyNoOutstandingRequest();
  });

  it('should be resolved a promise with status 200', () => {

    remoteBackend.when('GET', 'http://google.fr')
      .respond(200, {});

    service.loadRessource('http://google.fr').then((res) => {
      expect(res.status).toEqual(200);
      remoteBackend.flush();
    });
  });

});

那应该涵盖这段代码:

loadRessource(ressource) {
    return this.http.get(ressource);
  }

然而,由于我在使用httBackend刷新时出现问题,似乎我遗漏了一些东西:错误:未刷新的请求:1。

你能帮我做这个测试吗?

1 个答案:

答案 0 :(得分:1)

作为it的第二个参数的函数需要一个参数来告诉mocha它的异步。刷新后,调用回调。

it('should be resolved a promise with status 200', done => {

remoteBackend.when('GET', 'http://google.fr')
  .respond(200, {});

service.loadRessource('http://google.fr').then((res) => {
  expect(res.status).toEqual(200);
  remoteBackend.flush();
  done();
});

});