Sub topic 12
Testing Retries
This chapter assumes you can already configure provideHttpClientTesting, match requests with expectOne, and answer them with flush. It builds on those skills to test a service method that repeats a failed request.
What retry changes
The service method under test is getUserWithRetry:
getUserWithRetry(id: number): Observable<User> {
return this.http.get<User>(`/api/users/${id}`).pipe(retry(2));
}retry(2) means "resubscribe up to two more times after an error". The method can therefore send up to three requests: the original plus two retries. Each resubscription makes HttpClient send a brand-new request, so the test must answer each one separately.
Testing the success path
The retry happens synchronously. When you flush an error, retry resubscribes immediately, so the next request is already pending when flush returns. Call expectOne again for each attempt.
import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { User, UserService } from './user.service';
describe('UserService retries', () => {
let service: UserService;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
service = TestBed.inject(UserService);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
});
it('retries a failed request and succeeds on the third attempt', () => {
let result: User | undefined;
service.getUserWithRetry(1).subscribe((user) => (result = user));
httpTesting
.expectOne('/api/users/1')
.flush('fail', { status: 500, statusText: 'Server Error' });
httpTesting
.expectOne('/api/users/1')
.flush('fail', { status: 500, statusText: 'Server Error' });
httpTesting.expectOne('/api/users/1').flush({ id: 1, name: 'Ada' });
expect(result).toEqual({ id: 1, name: 'Ada' });
});
});Nothing is emitted until the third flush. The test shows the caller sees one value, not three results.
Testing that retrying stops
A retry test is incomplete without the limit. Fail three times and check that the error reaches the subscriber:
it('gives up after three failed attempts', () => {
let status: number | undefined;
service.getUserWithRetry(1).subscribe({
error: (e) => (status = e.status),
});
for (let attempt = 0; attempt < 3; attempt++) {
httpTesting
.expectOne('/api/users/1')
.flush('fail', { status: 500, statusText: 'Server Error' });
}
expect(status).toBe(500);
});Add this test inside the same describe block. The afterEach call to verify() now guards the limit. If the service retried a fourth time, a request would be left pending and verify() would fail the test.
Common mistakes
- Calling
expectOneonce. After the first flush, a retry is pending. A test that never answers it fails atverify()with an outstanding request. - Using
expectOnebefore a failure is flushed. Only one request exists at a time. Retries do not run in parallel, so you cannot match three requests up front. - Counting the original request as a retry.
retry(2)produces three requests. Off-by-one errors here make a test pass or fail for the wrong reason. - Retrying on a status you expect to be final.
retryreacts to every error, including 404 and 400. If only some errors should be retried, test one retryable and one non-retryable status.
Exercise
A service uses retry(3). How many requests can HttpTestingController see for one subscription, and what must the test do to make the subscriber receive the error?
Show answer
It can see four requests: the original and three retries. The test must flush all four with an error status, calling expectOne before each flush. After the fourth failure, retry stops and passes the error to the subscriber's error callback.