'How to mock HttpClient in a provided service in a component test in Angular?

Let's say I have a service that makes use of HttpClient,

@Injectable()
export class MyService {
  constructor(protected httpClient: HttpClient) { .. }
}

And then a component that makes use of this service.

@Component({
  selector: 'my-component'
})

export class SendSmsComponent {
  constructor(private MyService) { .. }
}

How to test this component while mocking the HttpClient and not the whole service?

TestBed.configureTestingModule({
  declarations: [MyComponent],
  providers: [
    { provide: MyService, useClass: MyService } // ?
  ]
}).compileComponents();

httpMock = TestBed.get(HttpTestingController); // ?


Solution 1:[1]

To mock HttpClient you can use HttpClientTestingModule with HttpTestingController

Sample code to accomplish the same

import { TestBed, ComponentFixture } from '@angular/core/testing';
import { Type } from '@angular/core';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { SendSmsComponent } from './send-sms/send-sms.component';
import { ApiService } from '@services/api.service';

describe('SendSmsComponent ', () => {
  let fixture: ComponentFixture<SendSmsComponent>;
  let app: SendSmsComponent;
  let httpMock: HttpTestingController;

  describe('SendSmsComponent ', () => {
    beforeEach(async () => {
      TestBed.configureTestingModule({
        imports: [
          HttpClientTestingModule,
        ],
        declarations: [
          SendSmsComponent,
        ],
        providers: [
          ApiService,
        ],
      });

      await TestBed.compileComponents();

      fixture = TestBed.createComponent(SendSmsComponent);
      app = fixture.componentInstance;
      httpMock = fixture.debugElement.injector.get<HttpTestingController>(HttpTestingController as Type<HttpTestingController>);

      fixture.detectChanges();
    });

    afterEach(() => {
      httpMock.verify();
    });

    it('test your http call', () => {
      const dummyUsers = [
        { name: 'John' },
      ];

      app.getUsers();
      const req = httpMock.expectOne(`${url}/users`);
      req.flush(dummyUsers);

      expect(req.request.method).toBe('GET');
      expect(app.users).toEqual(dummyUsers);
    });
  });
});

Solution 2:[2]

This is the approach I follow while testing HttpClient

  1. Create mock HttpClient object

    const httpClientSpy = jasmine.createSpyObj('HttpClient', ['post', 'get']);
    
  2. Injecting mock object in providers

    providers: [{ provide: HttpClient, useValue: httpClientSpy }]
    
  3. Return dummy valued within beforeEach() or it()

    httpClientSpy.post.and.returnValue(of({ status: 200, data: {} }));
    httpClientSpy.get.and.returnValue(of({ status: 200, data: {} }));
    
  4. Example test case

    it('should return data for abc endpoint', () => {
      service.methodWithHttpRequest().subscribe(data => expect(data.status).toBe(200));
    });
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Liam
Solution 2