Sub topic 5
Asserting on Observable results
This chapter assumes you know TypeScript, RxJS subscribe, Angular dependency injection, and how to run tests with the Angular CLI. It covers how to check the values a service returns through an Observable.
Why Observables need care in tests
A test function finishes when its last line runs. An Observable may emit later, after the test is over. If your assertion sits inside a subscribe callback that never runs, the test passes without checking anything. Every Observable test has to make sure the assertion actually executes.
Two things decide how to write the test:
- Synchronous Observables emit as soon as you subscribe. Examples are
of(1)or a stub that returns a ready value. - Asynchronous Observables emit later. An HTTP call is one. With
HttpTestingControlleryou control exactly when the response arrives, so the emission happens inside your test.
Pattern 1: capture, then assert
Store the value in a variable inside subscribe. Assert after the emission has happened, outside the callback.
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
describe('a synchronous Observable', () => {
it('doubles the emitted value', () => {
let result: number | undefined;
of(21)
.pipe(map((n) => n * 2))
.subscribe((value) => (result = value));
expect(result).toBe(42);
});
});The assertion sits outside the callback. If nothing was emitted, result stays undefined and the test fails. That is the behavior you want.
The HTTP tests in this tutorial use the same shape. The test subscribes, flushes the response, and then asserts:
let result: User | undefined;
service.getUser(1).subscribe((user) => (result = user));
httpTesting.expectOne('/api/users/1').flush({ id: 1, name: 'Ada' });
expect(result).toEqual({ id: 1, name: 'Ada' });flush delivers the response synchronously. By the next line, the callback has run.
Pattern 2: convert to a Promise
For a source that emits once and then completes, firstValueFrom turns the Observable into a Promise. You can then use an async test and await the value.
import { firstValueFrom } from 'rxjs';
it('works with promises through firstValueFrom', async () => {
const promise = firstValueFrom(service.getUser(1));
httpTesting.expectOne('/api/users/1').flush({ id: 1, name: 'Ada' });
expect(await promise).toEqual({ id: 1, name: 'Ada' });
});Order matters here. Call firstValueFrom first, because that subscribes and makes the request. Then flush. Then await. If you await before flushing, the test waits for a response that nobody sends and times out.
Pattern 3: collect several emissions
Some Observables emit more than once. Push each value into an array, then compare the array.
import { Subject } from 'rxjs';
it('collects every emission in order', () => {
const source = new Subject<number>();
const seen: number[] = [];
source.subscribe((n) => seen.push(n));
source.next(1);
source.next(2);
source.next(3);
expect(seen).toEqual([1, 2, 3]);
});Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Assertion only inside `subscribe` | The test passes even if nothing emits | Capture the value, assert outside |
| `await` before `flush` | The test times out | Flush first, then await |
| Never subscribing | The cold Observable does nothing and no request is sent | Subscribe, or use `firstValueFrom` |
| Using `firstValueFrom` on a source that never emits | The Promise never settles | Make sure the source emits or completes |
Exercise
A test calls const promise = firstValueFrom(service.getUser(1));, then expect(await promise).toEqual(...), and only afterwards calls httpTesting.expectOne('/api/users/1').flush(...). What happens, and how do you fix it?
Show answer
The test hangs until it times out. await promise waits for a response, but the flush that would deliver it comes after the await and never runs. Move the expectOne(...).flush(...) call above the await, so the response is delivered before the test waits on the Promise.
Exercise
Why is it risky to put expect(user).toEqual(...) only inside the subscribe callback of a synchronous-looking test?
Show answer
If the Observable never emits, the callback never runs. The expectation is never evaluated and the test passes without checking anything. Capture the value in a variable and assert after the emission, outside the callback.