I am writing a unit test with jest for a service method that makes an http request to a local server that runs on json-server in localhost:3000
This is the service method:
fetchData() {
return this.httpClient.get('http://localhost:3000/items');
}
And this is unit test for such method:
it('should retrieve an array of items', () => {
service.fetchData().subscribe((response) => {
expect(response).toEqual(mockItemList);
});
const request = httpController.expectOne({
method: 'GET',
url: 'http://localhost:3000/items'
})
request.flush(mockItemList);
});
Where:
- service is the service class
- mockItemList is a mocked array of items
- httpController is my instance of HttpTestingController.
When running the test, Jest returns the following error: Expected one matching request for criteria "Match method: GET, URL: http://localhost:3000/items", found 2 requests.
When I debug my application in Chrome, it correctly performs only 1 request, as seen in the Developer tools network tab and the service method is called only once.