Sub topic 11
Testing code that mixes signals and observables
Code that uses toSignal and toObservable is harder to test than code that uses only one of them. Three things get in the way. The interop functions need an injection context. toObservable emits from an effect, so it only emits when effects run. RxJS time operators such as debounceTime need a controlled clock. This chapter shows how to handle each one.
It assumes you can write basic Angular component tests with TestBed, and that you know fakeAsync and tick at a basic level. It also assumes you have read the earlier chapters on toSignal, toObservable and the debounced search pipeline. The examples use Jasmine syntax, which is the Angular CLI default. They work the same way in Jest.
What you need to control
A test for interop code has to control three things:
| Concern | Why it matters | Tool |
|---|---|---|
| Injection context | `toSignal` and `toObservable` throw if they run outside one | `TestBed.createComponent`, `TestBed.runInInjectionContext` |
| Effect timing | `toObservable` emits from an effect, so nothing emits until effects run | `fixture.detectChanges()`, `TestBed.tick()` |
| Virtual time | `debounceTime`, `interval` and `delay` wait on timers | `fakeAsync`, `tick(ms)` |
| HTTP | `switchMap` calls the server | `provideHttpClientTesting`, `HttpTestingController` |
TestBed.tick() runs change detection and pending effects. It is available in Angular 20 and later. In Angular 17 to 19, use TestBed.flushEffects() instead. The examples below use TestBed.tick().
Testing toSignal outside a component
A service or helper function that calls toSignal needs an injection context. A test body does not have one. TestBed.runInInjectionContext supplies it:
import { TestBed } from '@angular/core/testing';
import { toSignal } from '@angular/core/rxjs-interop';
import { BehaviorSubject, Subject } from 'rxjs';
describe('toSignal', () => {
it('follows a BehaviorSubject synchronously', () => {
const source$ = new BehaviorSubject(1);
const count = TestBed.runInInjectionContext(() =>
toSignal(source$, { requireSync: true }),
);
expect(count()).toBe(1);
source$.next(2);
expect(count()).toBe(2);
});
it('is undefined until the first emission', () => {
const source$ = new Subject<string>();
const value = TestBed.runInInjectionContext(() => toSignal(source$));
expect(value()).toBeUndefined();
source$.next('hello');
expect(value()).toBe('hello');
});
});toSignal updates its signal as soon as the observable emits. There is no effect in between, so these tests need no tick of either kind.
If the code under test already uses inject() in a constructor, create it with TestBed.inject(MyService). The service constructor then runs in an injection context on its own.
Testing errors and completion
A signal created by toSignal throws the observable's error when you read it. Test that behavior directly:
import { TestBed } from '@angular/core/testing';
import { toSignal } from '@angular/core/rxjs-interop';
import { Subject, catchError, of } from 'rxjs';
describe('toSignal errors and completion', () => {
it('throws the error when the signal is read', () => {
const source$ = new Subject<string>();
const value = TestBed.runInInjectionContext(() => toSignal(source$));
source$.error(new Error('boom'));
expect(() => value()).toThrowError('boom');
});
it('keeps a fallback value when catchError is used', () => {
const source$ = new Subject<string>();
const value = TestBed.runInInjectionContext(() =>
toSignal(
source$.pipe(catchError(() => of('fallback'))),
{ initialValue: 'loading' },
),
);
expect(value()).toBe('loading');
source$.error(new Error('boom'));
expect(value()).toBe('fallback');
});
it('keeps the last value after completion', () => {
const source$ = new Subject<number>();
const value = TestBed.runInInjectionContext(() =>
toSignal(source$, { initialValue: 0 }),
);
source$.next(5);
source$.complete();
expect(value()).toBe(5);
});
});The second test is the one to copy into your own suites. If a stream can fail, assert that your catchError leaves the signal readable. A template that reads a throwing signal breaks rendering, so this is a real bug and not a style issue.
Testing unsubscription
toSignal subscribes right away and unsubscribes when the surrounding injector is destroyed. You can check this by looking at Subject.observed, which is available in RxJS 7.2 and later:
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { toSignal } from '@angular/core/rxjs-interop';
import { Subject } from 'rxjs';
@Component({ selector: 'app-probe', template: '' })
class Probe {
source$ = new Subject<number>();
value = toSignal(this.source$);
}
describe('toSignal cleanup', () => {
it('unsubscribes when the component is destroyed', () => {
const fixture = TestBed.createComponent(Probe);
const { source$ } = fixture.componentInstance;
expect(source$.observed).toBeTrue();
fixture.destroy();
expect(source$.observed).toBeFalse();
});
});The subscription already exists before the first detectChanges(). It starts when the component is created, not when the template first reads the signal. If you use manualCleanup: true, this test would fail, because nothing unsubscribes. In that case the test is where you check that your own code unsubscribes.
Testing toObservable and skipped values
toObservable reads the signal inside an effect. Nothing is emitted until that effect runs. In a test, you run it yourself:
import { signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { toObservable } from '@angular/core/rxjs-interop';
describe('toObservable timing', () => {
it('emits only the latest value per flush', () => {
const n = signal(0);
const seen: number[] = [];
TestBed.runInInjectionContext(() => {
toObservable(n).subscribe((v) => seen.push(v));
});
n.set(1);
n.set(2);
expect(seen).toEqual([]);
TestBed.tick();
expect(seen).toEqual([2]);
n.set(3);
TestBed.tick();
expect(seen).toEqual([2, 3]);
});
});Notice three facts in this test:
- Right after subscribing,
seenis empty, because the effect has not run. - The first flush produces
2, not0, 1, 2. The effect runs once and sees the current value. - Every later flush produces one value, no matter how many
setcalls came before it.
If your production code must see every intermediate value, a signal is the wrong source. Use a Subject instead. A test like this one documents that choice.
Testing a signal, stream, signal pipeline with fake time
The debounced search from the previous chapter combines all four concerns. This test uses fakeAsync for the clock, detectChanges to run the effect, and HttpTestingController for the server.
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import {
HttpTestingController,
provideHttpClientTesting,
} from '@angular/common/http/testing';
import { Search } from './search';
describe('Search', () => {
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('waits for the debounce, then requests and shows results', fakeAsync(() => {
const fixture = TestBed.createComponent(Search);
const search = fixture.componentInstance;
fixture.detectChanges();
search.query.set('ang');
fixture.detectChanges();
tick(299);
http.expectNone('/api/search?q=ang');
tick(1);
const req = http.expectOne('/api/search?q=ang');
req.flush(['Angular', 'Angular Material']);
expect(search.results()).toEqual(['Angular', 'Angular Material']);
}));
});The order of steps matters.
- The first
detectChanges()runs thetoObservableeffect with the initial value''. This starts a 300 ms debounce timer. query.set('ang')followed by a seconddetectChanges()runs the effect again. The new value restarts the debounce timer.tick(299)leaves the timer one millisecond short, so no request exists yet.tick(1)fires it.flushcompletes the fake request, andtoSignalupdatesresultsat once.
To test the cancellation behavior of switchMap, set a second query after the first request is sent but before you flush it. Then check that the first request was cancelled:
const first = http.expectOne('/api/search?q=ang');
search.query.set('angu');
fixture.detectChanges();
tick(300);
expect(first.cancelled).toBeTrue();
http.expectOne('/api/search?q=angu').flush(['Angular']);Place this code after tick(1) and the first expectOne in the previous test, in place of the flush call.
Testing a time-based source
An interval never completes, so fakeAsync reports a pending periodic timer when the test ends. Clear it with discardPeriodicTasks():
import {
TestBed,
discardPeriodicTasks,
fakeAsync,
tick,
} from '@angular/core/testing';
import { Ticker } from './ticker';
describe('Ticker', () => {
it('counts seconds', fakeAsync(() => {
const fixture = TestBed.createComponent(Ticker);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Seconds: 0');
tick(3000);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Seconds: 2');
discardPeriodicTasks();
}));
});After 3000 ms the value is 2, not 3. interval(1000) emits 0 after the first second, 1 after the second and 2 after the third. The initialValue: 0 shown before that is separate from the stream's own first 0.
Replacing signals with fakes
When a component reads a signal from a service, you often do not need the real stream. Provide a fake with a writable signal and set values directly:
import { Injectable, signal } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class UserStore {
readonly name = signal('Ada');
}
// In the test:
// const store = TestBed.inject(UserStore);
// store.name.set('Grace');
// fixture.detectChanges();Setting a signal and calling detectChanges() is much simpler than building an observable chain. Reserve the full pipeline test for the one place that actually contains the interop code.
Common mistakes in interop tests
- No injection context. Calling
toSignaldirectly in anitblock throws. Wrap the call inTestBed.runInInjectionContext, or build the object throughTestBed.injectorcreateComponent. - Forgetting to flush effects. A
toObservablesubscriber that never fires usually means noTestBed.tick()ordetectChanges()ran after the signal changed. - Asserting before the debounce.
tickmust reach the full delay. Check the exact boundary, as intick(299)followed bytick(1). - Leaving HTTP requests unflushed.
http.verify()inafterEachfails the test if a request was never matched, which catches missingflushcalls. - Leaving timers running. Use
discardPeriodicTasks()forinterval, or complete the stream, sofakeAsynccan finish.
Exercise
A test sets query.set('a') on a component that pipes toObservable(this.query) through debounceTime(300). The test then calls tick(300) and expects an HTTP request, but expectOne finds none. What is missing, and why?
Show answer
Nothing ran the toObservable effect. The signal change only reaches the stream after an effect flush, so the debounce timer never started. Call fixture.detectChanges() (or TestBed.tick()) after query.set('a') and before tick(300). The effect then emits, the 300 ms timer starts, and the later tick(300) fires it.
Exercise
Write a test that proves a signal created by toSignal(source$, { initialValue: 'loading' }) shows 'loading' before the first emission and the new value afterwards. State how you create it so it has an injection context.
Show answer
Create it with TestBed.runInInjectionContext(() => toSignal(source$, { initialValue: 'loading' })), where source$ is a Subject<string>. Assert value() is 'loading', call source$.next('ready'), then assert value() is 'ready'. No tick is needed, because toSignal updates synchronously on each emission.
Exercise
A test calls n.set(1); n.set(2); n.set(3); on a signal wrapped by toObservable, then runs TestBed.tick() once. What does the subscriber record, and what would you change in the production code if all three values mattered?
Show answer
The subscriber records only 3, because the effect runs once and reads the current value. If every value matters, do not drive the stream from a signal. Push the values through an RxJS Subject (or BehaviorSubject) so each next call is delivered, and convert to a signal with toSignal if the template needs one.