Search⌘ K
AI Features

Mock API Calls

Explore techniques to mock API calls in Angular unit tests using HttpClientTestingModule. Learn to verify HTTP requests with HttpTestingController methods like expectOne, match, and flush to simulate responses without contacting external APIs.

When we test an Angular component, we mock the data services and dependencies. We also test the service to make sure that it behaves correctly and makes the correct API calls. In most cases, we don’t want to actually call the external API, so we can make use of HttpClientTestingModule, which we provide as a mock instead of HttpClientModule. HttpClientTestingModule makes it easy to make assertions about the API calls we expect and also to return mock data where required.

In order to use HttpClientTestingModule, we need to do two things:

  1. Import HttpClientTestingModule in our TestBed configuration.
  2. Fetch a copy of HttpTestingController from the TestBed dependency injection.

Note: This technique works only when we use Angular’s HttpClientModule to make our HTTP ...