Dùng provideHttpClient() cùng provideHttpClientTesting() để thay backend thật bằng test backend, rồi dùng HttpTestingController để assert request và flush response.
Ví dụ:
typescript
TestBed.configureTestingModule({
providers: [UserApi, provideHttpClient(), provideHttpClientTesting()],
})
const api = TestBed.inject(UserApi)
const http = TestBed.inject(HttpTestingController)
const promise = firstValueFrom(api.getUser("42"))
http.expectOne("/api/users/42").flush({ id: "42", name: "Ada" })
await expectAsync(promise).toBeResolved()
http.verify()Thứ tự provider quan trọng: provideHttpClient() phải đứng trước provideHttpClientTesting().