# Component, harness and store test recipes

Open this for the exact form of a test against Material, a `@defer` block, a route, a Signal Form, a resource or a store. Verified 2026-09 against https://angular.dev/guide/testing/using-component-harnesses, https://angular.dev/api/core/testing/TestBed and https://testing-library.com/docs/angular-testing-library/api.

## 1. CDK component harnesses

```ts
import { TestBed } from '@angular/core/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import type { HarnessLoader } from '@angular/cdk/testing';
import { MatButtonHarness } from '@angular/material/button/testing';
import { MatDialogHarness } from '@angular/material/dialog/testing';
import { OrderActions } from './order-actions';

it('opens the confirm dialog and returns the result', async () => {
  const fixture = TestBed.createComponent(OrderActions);
  const loader: HarnessLoader = TestbedHarnessEnvironment.loader(fixture);
  const rootLoader = TestbedHarnessEnvironment.documentRootLoader(fixture);

  await (await loader.getHarness(MatButtonHarness.with({ text: /cancel order/i }))).click();

  const dialog = await rootLoader.getHarness(MatDialogHarness);
  expect(await dialog.getTitleText()).toMatch(/cancel this order/i);
});
```

- `TestbedHarnessEnvironment` comes from `@angular/cdk/testing/testbed`; `HarnessLoader` and the shared symbols from `@angular/cdk/testing`.
- `loader(fixture)` is rooted at the component; **`documentRootLoader(fixture)` is what you need for dialogs, menus, tooltips and snackbars**, because the CDK overlay renders outside the component's DOM. Reaching for the wrong loader is the single most common harness mistake.
- Harness methods are async and wait for stability, which removes most overlay-timing flake.
- `getAllHarnesses` for every instance, `MatXHarness.with({ selector, text })` to narrow.

Use a harness when the component under test is mostly Material. Use Testing Library role queries for your own markup — they double as an accessibility assertion.

## 2. `@defer` blocks

```ts
import { DeferBlockBehavior, DeferBlockState, TestBed } from '@angular/core/testing';
import { Dashboard } from './dashboard';

it('renders the chart once the defer block completes', async () => {
  TestBed.configureTestingModule({ deferBlockBehavior: DeferBlockBehavior.Manual });
  const fixture = TestBed.createComponent(Dashboard);
  const [block] = await fixture.getDeferBlocks();

  await block.render(DeferBlockState.Placeholder);
  expect(fixture.nativeElement.textContent).toContain('Loading chart');

  await block.render(DeferBlockState.Complete);
  expect(fixture.nativeElement.querySelector('app-chart')).toBeTruthy();
});
```

`DeferBlockBehavior.Playthrough` lets the real triggers fire instead, which is what you want for a test about the *trigger* rather than the content.

## 3. Routing

```ts
import { TestBed } from '@angular/core/testing';
import { RouterTestingHarness } from '@angular/router/testing';
import { provideRouter } from '@angular/router';
import { provideLocationMocks } from '@angular/common/testing';
import { routes } from './app.routes';
import { OrderDetail } from './features/orders/pages/order-detail';

it('binds the :id route param to the component input', async () => {
  TestBed.configureTestingModule({ providers: [provideRouter(routes), provideLocationMocks()] });
  const harness = await RouterTestingHarness.create();
  const component = await harness.navigateByUrl('/orders/42', OrderDetail);
  expect(component.id()).toBe('42');
});
```

This is the only way to test that `withComponentInputBinding()` is wired correctly, because the binding happens during navigation, not construction.

For a guard, skip routing entirely:

```ts
import { TestBed } from '@angular/core/testing';
import { Router, UrlTree, provideRouter, type ActivatedRouteSnapshot, type RouterStateSnapshot } from '@angular/router';
import { authGuard } from './auth-guard';
import { AuthStore } from '../core/auth/auth-store';

const anonymous = { isSignedIn: () => false };

it('redirects an anonymous user to /login', () => {
  TestBed.configureTestingModule({ providers: [provideRouter([]), { provide: AuthStore, useValue: anonymous }] });
  const result = TestBed.runInInjectionContext(() =>
    authGuard({} as ActivatedRouteSnapshot, { url: '/orders' } as RouterStateSnapshot));

  expect(result).toBeInstanceOf(UrlTree);
  expect(TestBed.inject(Router).serializeUrl(result as UrlTree)).toBe('/login');
});
```

## 4. Signal Forms

Test through the DOM, because that is what the user touches:

```ts
import { render, screen } from '@testing-library/angular';
import userEvent from '@testing-library/user-event';
import { UserEditForm } from './user-edit-form';

it('blocks submit until the email is valid', async () => {
  const user = userEvent.setup();
  const { fixture } = await render(UserEditForm);

  await user.type(screen.getByLabelText(/email/i), 'not-an-email');
  await user.tab();
  await fixture.whenStable();

  expect(await screen.findByText(/valid email/i)).toBeInTheDocument();
  expect(screen.getByRole('button', { name: /save/i })).toBeDisabled();
});
```

Assert on form state (`f.email().invalid()`, `f().valid()`) only where the form object is the component's public API — a reusable form component that emits its validity, for example. Never assert that `required()` itself works; that is Angular's test.

## 5. Resources and HTTP

```ts
const http = TestBed.inject(HttpTestingController);
http.expectOne('/api/orders/42').flush(orderFixture);
await fixture.whenStable();

expect(component.order.hasValue()).toBe(true);
expect(component.order.value().number).toBe('A-42');
expect(component.order.isLoading()).toBe(false);
```

For the error path, `flush(null, { status: 500, statusText: 'Server Error' })` and assert `error()` plus whatever the template renders. Call `http.verify()` in `afterEach` so a stray extra request fails the test that caused it rather than the next one.

## 6. NgRx SignalStore

```ts
import { TestBed } from '@angular/core/testing';
import { patchState } from '@ngrx/signals';
import { unprotected } from '@ngrx/signals/testing';
import { OrdersStore } from './orders-store';
import { OrdersApi } from './orders-api';

it('filters by the query', () => {
  TestBed.configureTestingModule({ providers: [OrdersStore, { provide: OrdersApi, useValue: apiStub }] });
  const store = TestBed.inject(OrdersStore);

  patchState(unprotected(store), { orders: [{ id: '1', number: 'A-1' }, { id: '2', number: 'B-2' }] });
  store.setQuery('A-');

  expect(store.visible().map((o) => o.id)).toEqual(['1']);
});
```

`unprotected` (from `@ngrx/signals/testing`) is how you seed protected state without going through async methods. Use it for arranging; never for asserting — assert through the store's public signals so the test still describes behaviour.

For `rxMethod`-driven loads, provide a stub API returning a synchronous observable (`of(...)`) and assert the settled state; that keeps the test free of timer control.

**Classic NgRx Store:** reducers are pure functions — call them directly. Effects use `provideMockActions` and `firstValueFrom`. Components use `provideMockStore({ initialState })` with `overrideSelector`.

## 7. Stubbing a heavy child

```ts
import { Component, ChangeDetectionStrategy, input } from '@angular/core';

@Component({
  selector: 'app-chart',                       // same selector as the real one
  template: '<div data-stub="chart"></div>',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
class ChartStub {
  readonly series = input.required<readonly number[]>();
}

await render(Dashboard, { imports: [ChartStub] });   // overrides the real import
```

Give the stub the same inputs as the real component, so a renamed input breaks the test instead of silently doing nothing. Stub only for weight or side effects — a stubbed child is untested integration.
