Unit testing HttpClientModule in Angular 4.3: undefined return value from HttpTestingController.expectOne (url)

I am trying to figure out how to use the mocking functionality provided as part of the new one HttpClientModule

. My test code matches exactly what is shown in the existing documentation. However, the sample document is not complete - for example, at least there is no import statement for TestBad

and inject

. I assume this is true for HttpClient

from @ angular / common / http. My test code adds them.

This test fails because it req

ends in undefined after the call httpMock.expectOne

. I would be glad to know why this is possible.

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();
  }));
});

      

+3


source to share


1 answer


While I don't understand why this is the case, I got it working by removing the following from TestBed.configureTestingModule

:

providers: [HttpClient, HttpTestingController]



I welcome any insight into why I need to add my own services to the collection providers

, but not HttpClient, HttpTestingController

.

+3


source







All Articles