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 HttpClientTestingModuleStep 1: Initialising the projectLet’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 serviceNow, 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 Structure Dependencies"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
|