Sub topic 12
Testing retries
This chapter assumes you can write a basic HttpTestingController test. You should know how expectOne and flush work, and you should know that retry is an RxJS operator. The service is the UserService from the earlier chapters, with its getUserWithRetry method.
What a retry test needs to prove
The retry operator resubscribes to its source Observable when the source errors. For HttpClient, each subscription sends a new request. A retry test therefore has to answer a different request at every step.
A useful retry test checks three behaviors:
- A failure followed by a success ends in success, and the caller never sees the intermediate error.
- Repeated failures end in an error once the retries run out.
- The number of requests matches the retry count.
You are not testing RxJS itself. You are testing that your service is configured to retry the right number of times, on the right errors, with the right delay.
How many requests does `retry(2)` send?
retry(2) means two retries after the first attempt. That is three requests in total.
| Setting | Requests sent when all fail | Error reaches the subscriber after |
|---|---|---|
| `retry(0)` or no retry | 1 | 1st failure |
| `retry(1)` | 2 | 2nd failure |
| `retry(2)` | 3 | 3rd failure |
Counting wrongly is a common source of off-by-one mistakes in tests. If your test answers only two failures to retry(2), the third request stays pending and verify() fails.
Success after failures
This test uses the setup from the earlier chapters: provideHttpClient(), provideHttpClientTesting(), and verify() in afterEach. It answers each request in order.
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' });
});The order of operations matters. The second request does not exist until you flush the first one with an error. If you call expectOne twice before flushing, the second call fails because only one matching request is pending. The test controls the pace of the retries.
Failure after the retries run out
Next, test that the error reaches the subscriber only after the last attempt. The assertions also confirm that nothing was emitted early.
it('gives up after three failed attempts', () => {
let status: number | undefined;
let emitted = false;
service.getUserWithRetry(1).subscribe({
next: () => (emitted = true),
error: (e: HttpErrorResponse) => (status = e.status),
});
for (let attempt = 1; attempt <= 3; attempt++) {
expect(status).toBeUndefined();
httpTesting
.expectOne('/api/users/1')
.flush('fail', { status: 500, statusText: 'Server Error' });
}
expect(status).toBe(500);
expect(emitted).toBe(false);
httpTesting.expectNone('/api/users/1');
});The loop checks that status is still undefined before each flush. After the third failure the error arrives. expectNone confirms the service did not send a fourth request.
Add import { HttpErrorResponse } from '@angular/common/http'; at the top of the spec if it is not already there.
Retrying with a delay
Production code often waits between attempts. RxJS 7.3 and later accept a configuration object. The delay property takes a number of milliseconds, or a function that returns an Observable.
import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable, retry } from 'rxjs';
export interface User {
id: number;
name: string;
}
@Injectable({ providedIn: 'root' })
export class DelayedUserService {
private readonly http = inject(HttpClient);
getUser(id: number): Observable<User> {
return this.http
.get<User>(`/api/users/${id}`)
.pipe(retry({ count: 2, delay: 1000 }));
}
}A real one-second wait would make the test slow, and a test that sleeps is fragile. Use fakeAsync and tick to move the clock forward without waiting:
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { DelayedUserService, User } from './delayed-user.service';
describe('DelayedUserService', () => {
let service: DelayedUserService;
let httpTesting: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
service = TestBed.inject(DelayedUserService);
httpTesting = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpTesting.verify();
});
it('waits one second before the second attempt', fakeAsync(() => {
let result: User | undefined;
service.getUser(1).subscribe((user) => (result = user));
httpTesting
.expectOne('/api/users/1')
.flush('fail', { status: 503, statusText: 'Unavailable' });
httpTesting.expectNone('/api/users/1');
tick(999);
httpTesting.expectNone('/api/users/1');
tick(1);
httpTesting.expectOne('/api/users/1').flush({ id: 1, name: 'Ada' });
expect(result).toEqual({ id: 1, name: 'Ada' });
}));
});The test checks that no request exists at 999 ms and that one appears at 1000 ms. If a timer is still scheduled when a fakeAsync test ends, Angular fails the test with a "timer(s) still in the queue" error. That error means your test stopped answering requests before the retry sequence finished.
Retrying only some errors
Retrying a 404 or a 400 wastes requests, because the server will give the same answer again. A function passed as delay can decide per error. Return an Observable to retry, or throw to stop.
import { HttpErrorResponse } from '@angular/common/http';
import { retry, throwError, timer } from 'rxjs';
const retryServerErrors = retry({
count: 2,
delay: (error: HttpErrorResponse) =>
error.status >= 500 || error.status === 0
? timer(500)
: throwError(() => error),
});Use retryServerErrors in a .pipe(...) call in your service. Status 0 is a network failure, so the function retries those as well. Because a test can use error() and flush with a status, both paths are easy to cover:
| Test | How to simulate it | Expected requests |
|---|---|---|
| Server error is retried | `flush('x', { status: 500, statusText: 'Server Error' })`, then `tick(500)` | A second request appears |
| Client error is not retried | `flush('x', { status: 404, statusText: 'Not Found' })` | No second request, `expectNone` passes |
| Network failure is retried | `error(new ProgressEvent('error'))`, then `tick(500)` | A second request appears |
Write one test per row. The "not retried" case is the one people forget, and it is the one that protects you from accidental retry storms.
Pitfalls
- Retrying non-idempotent calls. A
POSTthat creates an order may have succeeded on the server even though the response was lost. Retrying it can create a duplicate. Test that your service does not retry such calls, or that it sends an idempotency key. - Asserting on the wrong request.
expectOnewith a URL string matches any method. If a retried request changes (for example, an interceptor adds a header only on later attempts), match with{ method, url }and checkreq.request.headersfor each attempt. - Flushing a request twice. Each
TestRequestcan be answered once. CallexpectOneagain to get the next request instead of reusing the old one. - Counting by loop instead of by intent. A loop like the one above is fine for a small, fixed count. If the count is the point of the test, name it with a constant so a reader sees why the loop runs three times.
- Skipping
verify(). Without it, a service that sends one request too many passes silently.
Exercise
A service method uses .pipe(retry(3)). A test flushes a 500 error for the first four requests and then calls httpTesting.verify(). What happens at each step, and how many requests does the service send in total?
Show answer
retry(3) allows the first attempt plus three retries, so four requests in total. The test flushes four 500 errors, and after the fourth the subscriber receives the error because retries are exhausted. No fifth request is sent, so verify() finds nothing pending and passes. If the test flushed only three errors, the fourth request would still be pending and verify() would throw.
Exercise
You change a service to retry({ count: 1, delay: 2000 }). Your existing test flushes a 500, then immediately calls expectOne for the second request, and it now fails. What two changes make the test pass without a real two-second wait?
Show answer
Wrap the test body in fakeAsync, and call tick(2000) after flushing the first error and before the second expectOne. The retry is scheduled on a timer, so the second request only exists once the fake clock reaches 2000 ms.