Testing With The Angular HttpClientTestingModule
Last Updated :
15 Jul, 2024
Testing is an important part of software development, ensuring that your application functions correctly and meets the requirements. Angular provides a powerful module for testing HTTP requests called HttpClientTestingModule
. This article will guide you through the process of setting up and using HttpClientTestingModule
to test HTTP requests in your Angular application.
Steps to Test with HttpClientTestingModule
Step 1: Initialising the project
Let's create an angular project, and navigate into it with the below commands:
ng new angular-test
cd angular-test
Step 2: Create an API service
Now, create an API service in the angular application using the below command, to write the code to fetch the data using a public API.
ng generate service api
We will write the logic to fetch data from a public API, like `https://jsonplaceholder.typicode.com` to fetch users data.
Project structure
Folder StructureDependencies
"dependencies": {
"@angular/animations": "^18.0.0",
"@angular/common": "^18.0.0",
"@angular/compiler": "^18.0.0",
"@angular/core": "^18.0.0",
"@angular/forms": "^18.0.0",
"@angular/platform-browser": "^18.0.0",
"@angular/platform-browser-dynamic": "^18.0.0",
"@angular/router": "^18.0.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
}
Example: To demonstrate testing angular HttpClient Testing Moudle.
JavaScript
// api.service.spec.ts
import { TestBed, inject } from '@angular/core/testing';
import {
HttpClientTestingModule,
HttpTestingController
} from '@angular/common/http/testing';
import { UserService } from './api.service';
import { HttpEvent, HttpEventType } from '@angular/common/http';
describe('ApiService', () => {
let service: UserService;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [UserService]
});
service = TestBed.inject(UserService);
});
it(
'should get users',
inject(
[HttpTestingController, UserService],
(httpMock: HttpTestingController, userService: UserService) => {
const mockUsers = [
{ name: 'Alice', website: 'example.com' },
{ name: 'Bob', website: 'example.org' }
];
userService.getData().subscribe((event: HttpEvent<any>) => {
switch (event.type) {
case HttpEventType.Response:
expect(event.body).toEqual(mockUsers);
}
});
const mockReq = httpMock.expectOne(userService.url);
expect(mockReq.cancelled).toBeFalsy();
expect(mockReq.request.responseType).toEqual('json');
mockReq.flush(mockUsers);
httpMock.verify();
}
)
);
});
JavaScript
//app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { UserService } from './api.service';
import { HttpEvent, HttpEventType } from '@angular/common/http';
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
templateUrl: './app.component.html',
styleUrl: './app.component.css'
})
export class AppComponent {
title = 'angular-test-2';
users: any = [];
constructor(private userService: UserService) { }
ngOnInit() {
this.fetchUsers();
}
fetchUsers() {
this.userService.getData().subscribe((event: HttpEvent<any>) => {
if (event.type === HttpEventType.Response) {
this.users = event.body;
}
});
}
}
JavaScript
// api.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class UserService {
url = 'https://jsonplaceholder.typicode.com/users';
constructor(private http: HttpClient) { }
getData() {
const req = new HttpRequest('GET', this.url, {
reportProgress: true
});
return this.http.request(req);
}
}
Run the test using the below command:
ng test --browsers=ChromeHeadless --include="src/app/api.service.spec.ts"
Output
Testing with the Angular HttpClientTestingModule
Similar Reads
How To Use HttpClient in Angular? In Angular, the HttpClient module is used to make HTTP requests to backend services. It simplifies communication with APIs, allowing developers to interact with RESTful services, send and receive data, and handle responses effectively. This article will guide you through setting up HttpClient, makin
6 min read
How to use services with HTTP methods in Angular v17? In Angular 17, services play an important role in managing HTTP requests to backend servers. By encapsulating HTTP logic within services, you can maintain clean, modular, and testable code. In this article, we'll explore how to use services to handle HTTP requests effectively in Angular 17 applicati
3 min read
How to send REST response to html in Angular ? In this article, we will see how to send API responses using HttpClient Module to an HTML using Angular, along with understanding the basic implementation through the examples.Angular is a JavaScript framework through which we can create reactive single-page web applications. For implementation, we
3 min read
Using a http service in Angular 17 with standalone components In Angular 17, they've introduced standalone components, which change how you build and organize Angular applications. These components are self-sufficient and can be used on their own without being tied to a specific NgModule. But, sometimes, when you're working with these standalone components, yo
3 min read
Navigating API Testing with Postman API(Application Programming Interface) testing plays a pivotal role in the software development lifecycle, ensuring the seamless functionality of APIs and safeguarding against potential issues. Postman, a comprehensive API development and testing tool, offers a range of features to streamline and en
6 min read
Postman Vs Thunder Client - API Testing Tools When it comes to API testing, Postman and Thunder Client are the first choices for developers. Postman has a powerful set of features that can be used to create, test, and automate APIs, while Thunder Client is a lightweight, VS Code extension focused on simplicity and ease of use for quick API test
3 min read