This test checks that DataService.getData() sends a GET request to 'api/data' and receives the expected mock data.
import { TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
class DataService {
constructor(private http: HttpClient) {}
getData() {
return this.http.get<{id: number; name: string}>('api/data');
}
}
describe('DataService with HttpTestingController', () => {
let service: DataService;
let httpTestingController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [DataService]
});
service = TestBed.inject(DataService);
httpTestingController = TestBed.inject(HttpTestingController);
});
it('should fetch data with GET request', (done) => {
const mockResponse = {id: 1, name: 'Test Item'};
service.getData().subscribe(data => {
expect(data).toEqual(mockResponse);
done();
});
const req = httpTestingController.expectOne('api/data');
expect(req.request.method).toBe('GET');
req.flush(mockResponse);
httpTestingController.verify();
});
});