Sub topic 11
Testing code that mixes signals and observables
This chapter assumes you know toSignal and toObservable, and that you have written basic Angular tests with TestBed. Tests for interop code fail for three reasons: there is no injection context, effects have not run yet, or timers have not advanced.
What changes when you test interop code
toSignal and toObservable need an injection context. A bare it() callback does not have one, so calling either function there throws. TestBed.runInInjectionContext gives you one.
toSignal is synchronous. Once the source emits, the signal holds the value. toObservable is different because it emits from an effect. The effect runs only when Angular flushes effects, so your test must trigger that flush.
| What you test | What the test needs |
|---|---|
| `toSignal` in a service or helper | `TestBed.runInInjectionContext` |
| `toObservable` in a service or helper | `TestBed.runInInjectionContext`, then `TestBed.tick()` after each change |
| `toObservable` in a component | `fixture.detectChanges()` after each change |
| `debounceTime` or other timers | `fakeAsync` and `tick(ms)` |
| HTTP calls in a pipeline | `provideHttpClientTesting` and `HttpTestingController` |
Testing toSignal
Drive the source with a Subject and read the signal directly. No flush is needed.
import { TestBed } from '@angular/core/testing';
import { toSignal } from '@angular/core/rxjs-interop';
import { Subject } from 'rxjs';
describe('toSignal', () => {
it('reflects emissions synchronously', () => {
const source$ = new Subject<number>();
const value = TestBed.runInInjectionContext(() =>
toSignal(source$, { initialValue: 0 }),
);
expect(value()).toBe(0);
source$.next(5);
expect(value()).toBe(5);
});
it('throws on read after the source errors', () => {
const source$ = new Subject<number>();
const value = TestBed.runInInjectionContext(() => toSignal(source$));
source$.error(new Error('boom'));
expect(() => value()).toThrow();
});
});The second test pins down the error behavior. If your code is meant to survive errors, test the version with catchError in the pipe and assert that the fallback value appears.
Testing toObservable
An effect must run before the observable emits. In Angular 20 and later, TestBed.tick() flushes pending effects. Older versions use TestBed.flushEffects().
import { TestBed } from '@angular/core/testing';
import { signal } from '@angular/core';
import { toObservable } from '@angular/core/rxjs-interop';
describe('toObservable', () => {
it('emits only the latest value per flush', () => {
const n = signal(0);
const seen: number[] = [];
TestBed.runInInjectionContext(() => {
toObservable(n).subscribe((v) => seen.push(v));
});
TestBed.tick();
n.set(1);
n.set(2);
TestBed.tick();
expect(seen).toEqual([0, 2]);
});
});The expected array [0, 2] documents the skipped value 1. A test like this protects you if someone later assumes every set produces an emission.
Testing the debounced search pipeline
The search component from the pipeline chapter combines all three concerns: a signal, a timer and HTTP. Use fakeAsync to control the debounce and HttpTestingController to answer requests.
A component's effects run during change detection of that component. Call fixture.detectChanges() after each signal change, not TestBed.tick().
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', () => {
it('sends one request for the last query after the debounce', fakeAsync(() => {
TestBed.configureTestingModule({
providers: [provideHttpClient(), provideHttpClientTesting()],
});
const http = TestBed.inject(HttpTestingController);
const fixture = TestBed.createComponent(Search);
const search = fixture.componentInstance;
fixture.detectChanges();
search.query.set('a');
fixture.detectChanges();
search.query.set('ab');
fixture.detectChanges();
tick(300);
const req = http.expectOne(
(r) => r.url === '/api/search' && r.params.get('q') === 'ab',
);
req.flush(['abc', 'abd']);
expect(search.results()).toEqual(['abc', 'abd']);
http.verify();
}));
});http.verify() fails the test if any unexpected request was made. That confirms the debounce dropped the earlier query 'a'. If expectOne finds no request, you most likely forgot a detectChanges() call or tick(300).
Common test failures
NG0203(injection context error): the test calledtoSignalortoObservableoutsiderunInInjectionContext. Wrap the call.- The observable never emits: no effect flush happened. Add
TestBed.tick()orfixture.detectChanges(). 1 timer(s) still in the queue: the debounce timer was not advanced. Calltick(300), orflush()to drain every pending timer.- No pending HTTP request: the debounce delay has not elapsed yet. Advance the clock before
expectOne.
Exercise
A test sets a signal three times in a row, then reads values from toObservable(sig).subscribe(...) without flushing anything. The subscriber has received nothing. Why, and what should you add?
Show answer
toObservable emits from an effect, and no flush has happened. Call TestBed.tick() for a service-level test, or fixture.detectChanges() for a component. Only the latest value emits after the flush, because the earlier set calls happened in the same tick.