Sub topic 5
Asserting on Observable results
This chapter assumes you know TypeScript, Angular services with dependency injection, the RxJS subscribe method, and how to run tests with the Angular CLI. You will learn how to check the values, errors, and completion of an Observable inside a unit test, and which pattern fits which situation.
Why Observables need care in tests
A test function finishes when its last line runs. An Observable can emit later, after that last line has already run. If an assertion sits inside a subscribe callback that never fires, the test passes without checking anything. This is the most common source of false-positive tests with RxJS.
Two facts guide every pattern below:
- Some Observables are synchronous. They emit during
subscribe, before the next line runs. Examples areof(1, 2)and aBehaviorSubject. - Some Observables are asynchronous. They emit later, after a timer, a promise, or an HTTP response. In Angular tests, an HTTP Observable emits only after you call
flushon the test request.
Before you choose a pattern, decide which kind you are testing. Then decide what you want to assert: the emitted values, the error, or the completion.
Pattern 1: Capture the value in a variable
The simplest pattern is to subscribe, store what arrives, and assert after the trigger. You have already seen it in the UserService HTTP test.
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
export function doubled(source: Observable<number>): Observable<number> {
return source.pipe(map((n) => n * 2));
}
describe('doubled', () => {
it('doubles a synchronous value', () => {
let result: number | undefined;
doubled(of(21)).subscribe((n) => (result = n));
expect(result).toBe(42);
});
});This works because of(21) emits synchronously. For an HTTP call, you declare the variable, subscribe, flush the request, and only then assert.
The weakness is the initial undefined. If the value never arrives, the failure message says "expected undefined to be 42". That is a correct failure but not a descriptive one. Keep the variable's type as T | undefined so TypeScript reminds you that it may be unset.
Pattern 2: Collect every emission
When the Observable emits several values, push each one into an array and compare the whole array.
import { of } from 'rxjs';
import { map } from 'rxjs/operators';
describe('multiple emissions', () => {
it('collects every value in order', () => {
const values: number[] = [];
let completed = false;
of(1, 2, 3)
.pipe(map((n) => n * 10))
.subscribe({
next: (n) => values.push(n),
complete: () => (completed = true),
});
expect(values).toEqual([10, 20, 30]);
expect(completed).toBe(true);
});
});Comparing the full array checks the count, the order, and the values in one assertion. Passing an observer object with next, error, and complete lets you record all three outcomes.
An HTTP Observable emits exactly one value and then completes. For those, Pattern 1 is enough. Use the array pattern for streams such as search-as-you-type results or state streams.
Pattern 3: Convert to a Promise
For async test functions, convert the Observable to a Promise and await it. firstValueFrom resolves with the first emission. lastValueFrom waits for completion and resolves with the last emission.
import { firstValueFrom, lastValueFrom, of } from 'rxjs';
describe('promise conversion', () => {
it('awaits the first value', async () => {
expect(await firstValueFrom(of(1, 2, 3))).toBe(1);
});
it('awaits the last value after completion', async () => {
expect(await lastValueFrom(of(1, 2, 3))).toBe(3);
});
});Errors become Promise rejections, so you can assert them with rejects in Jasmine or Jest.
import { firstValueFrom, throwError } from 'rxjs';
it('rejects when the Observable errors', async () => {
const failing = throwError(() => new Error('boom'));
await expectAsync(firstValueFrom(failing)).toBeRejectedWithError('boom');
});expectAsync is the Jasmine API. In Jest, write await expect(firstValueFrom(failing)).rejects.toThrow('boom').
The ordering trap with HTTP
With HTTP, create the promise before you flush, and await it after. The request is only sent when something subscribes, and firstValueFrom subscribes immediately.
it('subscribes first, flushes second, awaits last', async () => {
const promise = firstValueFrom(service.getUser(1)); // 1. subscribe
httpTesting.expectOne('/api/users/1').flush({ id: 1, name: 'Ada' }); // 2. answer
expect(await promise).toEqual({ id: 1, name: 'Ada' }); // 3. await
});If you write await firstValueFrom(service.getUser(1)) on the first line, the test waits for a response that you have not yet supplied. It hangs until the test timeout.
Pattern 4: Assert errors and completion
An Observable ends in one of three ways: it keeps going, it completes, or it errors. A test for the failure path needs to prove that the error callback ran. If the Observable unexpectedly succeeds, a test that only has an error handler passes silently.
import { Observable, throwError } from 'rxjs';
function failing(): Observable<number> {
return throwError(() => new Error('nope'));
}
describe('error path', () => {
it('reports the error and does not emit', () => {
const values: number[] = [];
let caught: Error | undefined;
failing().subscribe({
next: (n) => values.push(n),
error: (e: Error) => (caught = e),
});
expect(values).toEqual([]);
expect(caught?.message).toBe('nope');
});
});Asserting on caught after the subscription is what makes this test meaningful. If you wrote expect(e.message).toBe('nope') inside the error callback and the callback never ran, the test would pass without checking anything.
Jasmine and Jest differ here. Jasmine's done callback and Jest's expect.assertions(n) exist to catch exactly this case. Recording results in variables and asserting after the trigger needs neither.
Pattern 5: Use `done` for callbacks
Jasmine and Jest support a done argument. The test does not finish until you call done(). This guards against the never-fires problem because a missing call times out.
import { of } from 'rxjs';
it('finishes when the callback calls done', (done) => {
of('ready').subscribe((value) => {
expect(value).toBe('ready');
done();
});
});There is a catch. If an expect inside the callback throws, done is never called, and you get a timeout instead of a clear assertion message. In modern code, prefer a Promise with async/await. Use done only when you are maintaining older tests.
Testing time-based Observables
Observables that use delay, debounceTime, or interval need control over time. Angular's fakeAsync and tick replace the real clock.
import { fakeAsync, tick } from '@angular/core/testing';
import { of } from 'rxjs';
import { delay } from 'rxjs/operators';
describe('delayed emission', () => {
it('emits after the delay elapses', fakeAsync(() => {
let result: string | undefined;
of('late').pipe(delay(1000)).subscribe((v) => (result = v));
expect(result).toBeUndefined();
tick(999);
expect(result).toBeUndefined();
tick(1);
expect(result).toBe('late');
}));
});tick(ms) advances the fake clock. The test runs instantly, and the boundary checks at 999 and 1000 milliseconds prove the exact timing. Leaving a pending timer at the end of a fakeAsync test raises an error, which helps you catch forgotten cleanup. If you see "1 timer(s) still in the queue", either tick far enough or call flush() from @angular/core/testing.
Choosing a pattern
| Situation | Pattern | Why |
|---|---|---|
| One value, synchronous or after `flush` | Variable capture | Shortest and clearest |
| Several values over time | Collect into an array | One assertion checks count and order |
| `async` test, want a rejection check | `firstValueFrom` or `lastValueFrom` | Reads top to bottom |
| Failure path | Observer with `error`, assert after | Cannot pass silently |
| Timers, `delay`, `debounceTime` | `fakeAsync` with `tick` | No real waiting |
Common mistakes
- Asserting inside a callback that may never run. Record, then assert after the trigger.
- Awaiting before flushing. The HTTP test hangs because no response exists yet.
- Forgetting to subscribe. A cold Observable such as one from
HttpClientsends nothing until subscribed. ThenexpectOnefails with "Expected one matching request, found none". - Using
firstValueFromon an empty Observable. It rejects with anEmptyErrorif the stream completes without emitting. Pass adefaultValueoption when emptiness is valid. - Checking only the happy path. Write one test for the error callback, so a handler that is missing or broken is detected.
Summary
Decide first whether the Observable is synchronous or asynchronous. Capture results in variables or arrays and assert after the trigger. Convert to a Promise when an async test reads better, and subscribe before you flush. Use fakeAsync for time. Always include at least one test that proves the error path runs.
Exercise
A test calls service.getUser(1).subscribe({ next: (u) => expect(u.name).toBe('Ada') }) and then calls httpTesting.expectOne('/api/users/1').flush({ id: 1, name: 'Bob' }). The test passes. Name two problems, and say how you would restructure it.
Show answer
First, the assertion lives inside the next callback. An exception thrown there may not fail the test cleanly, and if the callback never ran the test would pass without checking anything. Second, the test flushes Bob but expects Ada, so the assertion should fail. It appears to pass because the failure happens in a callback and is not reported against the test. Restructure by declaring let result: User | undefined;, subscribing with (user) => (result = user), flushing, and then writing expect(result).toEqual({ id: 1, name: 'Ada' }) after the flush. Alternatively, create const promise = firstValueFrom(service.getUser(1));, flush, and expect(await promise).... Either version fails visibly when the data does not match.
Exercise
Why does const user = await firstValueFrom(service.getUser(1)); httpTesting.expectOne('/api/users/1').flush(...) hang, and what is the fix?
Show answer
await pauses the test on the first line, so the line that flushes the response never runs. The Observable cannot emit without a response, so the test waits until it times out. The fix is to store the Promise without awaiting it (const promise = firstValueFrom(...)), flush the request, and then await promise.