To
mock HTTP requests in Angular unit tests, you can use the
`HttpClientTestingModule` and
`HttpTestingController` provided by Angular's testing utilities.
Here's an example to demonstrate how to mock an HTTP request in Angular:
Let's assume you have a service called `DataService` that makes HTTP requests using Angular's
`HttpClient`:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class DataService {
constructor(private http: HttpClient) {}
fetchData(): Promise<string> {
return this.http.get<string>('https://api.example.com/data').toPromise();
}
}
Now, let's write a unit test for the `DataService` and mock the HTTP request:
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { DataService } from './data.service';
describe('DataService', () => {
let service: DataService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [DataService]
});
service = TestBed.inject(DataService);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
it('should fetch data from the API', () => {
const mockResponse = 'Mocked API response';
service.fetchData().then((data) => {
expect(data).toBe(mockResponse);
});
const req = httpMock.expectOne('https://api.example.com/data');
expect(req.request.method).toBe('GET');
req.flush(mockResponse);
});
});
In the test above, we import
`HttpClientTestingModule` and use it in the
`TestBed.configureTestingModule()` to configure the testing module. We also inject the
`HttpTestingController` to interact with the HTTP requests.
Inside the test, we call the `fetchData` method of the `DataService` and assert on the response data. Then, we use
`httpMock.expectOne()` to intercept the HTTP request and return a mock response using
`req.flush()`. Finally, we use
`httpMock.verify()` in the
`afterEach` block to ensure that no unexpected requests were made.
Conclusion :
By using the
`HttpClientTestingModule` and
`HttpTestingController`, we can mock the HTTP requests and control their responses, allowing us to test the behavior of the service without making actual API calls.
Note: Make sure to import the necessary testing utilities (`TestBed`, `HttpClientTestingModule`, `HttpTestingController`, etc.) from the appropriate packages (`@angular/core/testing`, `@angular/common/http/testing`, etc.) in your test files.