MyInternships.in

Testing, Performance & Deployment

Angular Testing Services and HTTP

HttpTestingController intercepts requests made through HttpClient so tests can assert what was requested and supply a fake response, without any real network access.


What is Testing Services and HTTP in Angular?

HttpTestingController intercepts requests made through HttpClient so tests can assert what was requested and supply a fake response, without any real network access.

Testing Services and HTTP example

Asserting the request and flushing a response
TypeScript
beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [provideHttpClient(), provideHttpClientTesting()],
  });
  service = TestBed.inject(JobService);
  httpMock = TestBed.inject(HttpTestingController);
});

it('requests jobs for a city', () => {
  service.getJobs('Pune').subscribe(jobs => expect(jobs.length).toBe(2));

  const req = httpMock.expectOne('/api/jobs?city=Pune');
  expect(req.request.method).toBe('GET');
  req.flush([{ id: '1' }, { id: '2' }]);
});

afterEach(() => httpMock.verify());   // fails if any request was unexpected

Key points to remember

  • expectOne asserts that exactly one matching request was made.
  • flush supplies the response body; error() simulates a failure.
  • verify() in afterEach catches requests you did not expect.

Common mistakes with Testing Services and HTTP

  • Forgetting to subscribe, so no request is ever made and expectOne fails.
  • Omitting verify() and letting stray requests pass unnoticed.

Angular Testing Services and HTTP— Interview Questions & FAQs

How do I test error handling in an Angular service?+

Call req.error(new ProgressEvent("error"), { status: 500 }) instead of flush, then assert that your catchError branch produced the expected message.

Related Angular Topics

Keep learning with these closely related lessons.

Ready to use your Angular skills?

Find verified Angular internships and fresher developer jobs across India.

Browse Angular Internships