How do you handle HTTP requests in Angular unit tests?
- Use HttpClientTestingModule and HttpTestingController to mock and
control HTTP requests.
Example:
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule]
});
httpTestingController = TestBed.inject(HttpTestingController);
});
it('should call GET API', () => {
service.getData().subscribe(data => {
expect(data).toEqual(mockData);
});
const req = httpTestingController.expectOne('api/data');
expect(req.request.method).toBe('GET');
req.flush(mockData);
httpTestingController.verify();
});