Angular 4.3中的单元测试HttpClientModule:来自HttpTestingController.expectOne(url)的未定义返回值

时间:2017-08-01 19:59:48

标签: angular unit-testing

我正在尝试了解如何使用作为新HttpClientModule的一部分提供的模拟功能。我的测试代码几乎完全匹配现有文档中显示的内容。但是,doc示例并不完整 - 例如,至少缺少TestBadinject的导入语句。我假设来自@ angular / common / http的HttpClient也是如此。我的测试代码添加了这些。

此测试失败,因为在req调用后httpMock.expectOne最终未定义。我很欣赏为什么会这样。

import { TestBed, inject } from '@angular/core/testing';
import { HttpClient } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

describe('HttpClientTestingModule', () => {
  beforeEach(() => TestBed.configureTestingModule({
    imports: [ HttpClientTestingModule ],
    providers: [ HttpClient, HttpTestingController]
  }));

  it('expects a GET request', inject([HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) => {
    http
      .get('/data')
      .subscribe(data => expect(data['name']).toEqual('Test Data'));

    const req = httpMock.expectOne('/data');
    expect(req).toBeDefined();
    expect(req.request.method).toEqual('GET');
    req.flush({name: 'Test Data'});
    httpMock.verify();
  }));
});

1 个答案:

答案 0 :(得分:7)

虽然我不明白为什么会这样,但是通过从TestBed.configureTestingModule删除以下内容,我得到了它的工作:

providers: [HttpClient, HttpTestingController]

我欢迎任何洞察我为什么需要将自己的服务添加到providers集合,而不是HttpClient, HttpTestingController