> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Testing patterns

Recipes for common tests with `@blotch/angular-lynx-testing-library`: inputs, directives, signal changes, events, host data, native APIs, error fallbacks and snapshots. Set up the library first, as in [Testing](/guide/testing.md).

## Set inputs

Pass `inputs` to `render()`, as a parent template would bind them:

```typescript title="src/app/greeting.test.ts"
import { Component, input } from '@angular/core';
import { LYNX_ELEMENTS } from '@blotch/angular-lynx';
import { render } from '@blotch/angular-lynx-testing-library';

@Component({
  selector: 'app-greeting',
  imports: [LYNX_ELEMENTS],
  template: `<text>Hello, {{ name() }}</text>`,
})
class Greeting {
  readonly name = input.required<string>();
}

it('greets by name', async () => {
  const { getByText, rerender } = await render(Greeting, {
    inputs: { name: 'Lynx' },
  });
  expect(getByText('Hello, Lynx')).toBeTruthy();

  await rerender({ inputs: { name: 'Angular' } });
  expect(getByText('Hello, Angular')).toBeTruthy();
});
```

- **Inputs are set before the first render**, so a required input has its value and `ngOnInit` sees it. No host component is needed.
- **Use the name a template binds.** An aliased input, such as `input('', { alias: 'class' })`, takes its alias: `inputs: { class: 'p-4' }`.
- **`rerender({ inputs })` keeps the component** and changes only the inputs you pass. It can change only inputs `render()` set, so give `render()` a starting value for any input you change later.

## Test a directive

`renderDirective()` puts a directive on a Lynx element, with no host component to write. It's the Lynx counterpart of Angular's `TestBed.createDirective()`:

```typescript title="src/app/highlight.test.ts"
import { Directive, input } from '@angular/core';
import {
  fireEvent,
  renderDirective,
  waitForUpdate,
} from '@blotch/angular-lynx-testing-library';

@Directive({
  selector: '[appHighlight]',
  host: {
    '[style.background-color]': 'color()',
    '[class.on]': 'on',
    '(bindtap)': 'on = !on',
  },
})
class Highlight {
  readonly color = input('yellow');
  on = false;
}

it('highlights its element and toggles on tap', async () => {
  const { container, directiveInstance } = await renderDirective(Highlight, {
    tagName: 'view',
    inputs: { color: 'red' },
  });
  const view = container.firstElementChild!;
  expect(view.getAttribute('style')).toContain('background-color: red');

  fireEvent.tap(view);
  await waitForUpdate();

  expect(directiveInstance.on).toBe(true);
  expect(view.getAttribute('class')).toBe('on');
});
```

- **`tagName` picks the element.** Leave it out when the selector names one: `text[appBold]` goes on a `<text>`.
- **The element is the `<page>`'s only child**, so `container.firstElementChild` is it.
- **Everything else is `render()`'s:** `inputs`, `rerender({ inputs })`, `providers`, the queries and cleanup. The [API reference](/api/testing-library/render.md#renderdirectiveresult) lists what it returns.

## Change a signal, then wait

Angular re-renders after a signal changes, not at the moment it changes. Call `waitForUpdate()` before you check the result:

```typescript title="src/app/label.test.ts"
import { Component, signal } from '@angular/core';
import { LYNX_ELEMENTS } from '@blotch/angular-lynx';
import { render, waitForUpdate } from '@blotch/angular-lynx-testing-library';

@Component({
  selector: 'app-label',
  imports: [LYNX_ELEMENTS],
  template: `<text>{{ label() }}</text>`,
})
class Label {
  readonly label = signal('initial');
}

it('shows the new label', async () => {
  const { container, componentRef } = await render(Label);
  expect(container.querySelector('text')!.textContent).toBe('initial');

  componentRef.instance.label.set('updated');
  await waitForUpdate();

  expect(container.querySelector('text')!.textContent).toBe('updated');
});
```

`waitForUpdate()` lets Angular's scheduled change detection run, then forces one more pass so every update reaches the tree.

## Fire events

`fireEvent` sends Lynx events, such as a tap, to an element:

```typescript title="src/app/counter.test.ts"
import { Component, signal } from '@angular/core';
import { LYNX_ELEMENTS } from '@blotch/angular-lynx';
import {
  fireEvent,
  render,
  waitForUpdate,
} from '@blotch/angular-lynx-testing-library';

@Component({
  selector: 'app-counter',
  imports: [LYNX_ELEMENTS],
  template: `
    <view (bindtap)="increment()">
      <text>{{ count() }}</text>
    </view>
  `,
})
class Counter {
  readonly count = signal(0);

  increment(): void {
    this.count.update((n) => n + 1);
  }
}

it('counts taps', async () => {
  const { container } = await render(Counter);

  fireEvent.tap(container.querySelector('view')!);
  await waitForUpdate();

  expect(container.querySelector('text')!.textContent).toBe('1');
});
```

- **Your handler runs right away.** `fireEvent.tap()` calls `increment()` before it returns.
- **A tap bubbles, as on a device.** Tap the `<text>` and the view's `(bindtap)` still runs. A `(catchtap)` on the way stops it.
- **The screen updates afterwards.** As on a device, Angular re-renders after the handler, so `await waitForUpdate()` before you check the tree.
- **Pass event data as the second argument.** Its properties are copied onto the event your handler receives. Lynx's `<input>` puts its text in `event.detail.value`, for example:

```typescript
fireEvent.input(input, { detail: { value: 'hello' } });
```

The [event reference](/api/testing-library/event-reference.md) lists every event `fireEvent` can send.

## Fake host data

No host app runs in a test, so InitData and GlobalData hold nothing. Provide a stand-in for `LynxInitData` or `LynxGlobalData` with the values you need:

```typescript title="src/app/welcome.test.ts"
import { Component, computed, inject, signal } from '@angular/core';
import { LYNX_ELEMENTS, LynxInitData } from '@blotch/angular-lynx';
import { render } from '@blotch/angular-lynx-testing-library';

@Component({
  selector: 'app-welcome',
  imports: [LYNX_ELEMENTS],
  template: `<text>Hi {{ userId() }}</text>`,
})
class Welcome {
  readonly #initData = inject(LynxInitData);
  readonly userId = computed(
    () => this.#initData.initData()?.['userId'] ?? 'guest',
  );
}

it('greets the user named in InitData', async () => {
  const { getByText } = await render(Welcome, {
    providers: [
      {
        provide: LynxInitData,
        useValue: { initData: signal({ userId: 'user_42' }) },
      },
    ],
  });

  expect(getByText('Hi user_42')).toBeTruthy();
});
```

`LynxTheme` and `LynxLocale` read GlobalData, so the same trick sets them. For example, `{ provide: LynxGlobalData, useValue: { globalData: signal({ theme: 'Dark' }) } }` makes `LynxTheme.isDarkMode()` return `true`.

## Fake native APIs

Services that call the phone answer as a phone without your native code would, or throw, in jsdom. A test has none of your app's native modules, so `LynxNativeModule.call()` resolves `undefined` and a native module's methods reject, and `LynxTextMeasure.measure()` throws. Provide fakes:

```typescript
import { LynxNativeModule, LynxTextMeasure } from '@blotch/angular-lynx';

const { getByText } = await render(ProfileHeader, {
  providers: [
    { provide: LynxNativeModule, useValue: { call: async () => 'device-123' } },
    { provide: LynxTextMeasure, useValue: { measure: () => ({ width: 120 }) } },
  ],
});
```

To test a service on its own, without rendering anything, use Angular's `TestBed` with the same providers. `ng test` runs `TestBed` tests as they are.

## Test an error fallback

`@boundary` works in tests with the error handler that `provideRenderer()` registers. Make the content throw, then look for the fallback:

```typescript title="src/app/price.test.ts"
import { Component, signal } from '@angular/core';
import { LYNX_ELEMENTS } from '@blotch/angular-lynx';
import { render, waitForUpdate } from '@blotch/angular-lynx-testing-library';

@Component({
  selector: 'app-price',
  imports: [LYNX_ELEMENTS],
  template: `
    @boundary {
      <text>{{ format(price()) }}</text>
    } @error {
      <text>Price unavailable</text>
    }
  `,
})
class Price {
  readonly price = signal(10);

  format(value: number): string {
    if (Number.isNaN(value)) throw new Error('Bad price');
    return `$${value}`;
  }
}

it('shows the fallback when the price is bad', async () => {
  const { getByText, componentRef } = await render(Price);

  componentRef.instance.price.set(Number.NaN);
  await waitForUpdate();

  expect(getByText('Price unavailable')).toBeTruthy();
});
```

The caught error doesn't fail the test, just as it doesn't stop the app on a device: `LynxErrorHandler` reports it to Lynx as a warning. To check which error the boundary caught, give the test an error handler that records it:

```typescript title="src/app/price.test.ts"
import { ErrorHandler, Service } from '@angular/core';
import { LynxErrorHandler } from '@blotch/angular-lynx';

@Service({ autoProvided: false })
class RecordingErrorHandler extends LynxErrorHandler {
  readonly caught: Error[] = [];

  override onViewError(error: Error): void {
    this.caught.push(error);
  }
}

it('catches the bad price', async () => {
  const handler = new RecordingErrorHandler();
  const { componentRef } = await render(Price, {
    providers: [{ provide: ErrorHandler, useValue: handler }],
  });

  componentRef.instance.price.set(Number.NaN);
  await waitForUpdate();

  expect(handler.caught.map((error) => error.message)).toEqual(['Bad price']);
});
```

## Snapshot tests

`asFragment()` copies the rendered Lynx element tree, ready for a snapshot:

```typescript
const { asFragment } = await render(Label);
expect(asFragment()).toMatchSnapshot();
```

Each call takes a new copy, so you can snapshot before and after a change.

## Reach into the component

`componentRef` is the rendered component's `ComponentRef`:

```typescript
const { componentRef } = await render(Label);

// Read a service from the app's injector.
const store = componentRef.injector.get(CartStore);

// Change state on the instance, then wait for the update.
componentRef.instance.label.set('updated');
await waitForUpdate();
```

To change an input, use [`rerender({ inputs })`](#set-inputs). `componentRef.setInput()` works too when `render()` set no inputs. Both need `ng test`, which compiles components ahead of time. Under plain Vitest, which compiles them at runtime, they can't reach signal inputs, so change writable signals on the instance there.

## Custom queries

Pass `queries` to add your own query helpers next to the standard ones:

```typescript
const queryByTag = (container: HTMLElement, tag: string) =>
  container.querySelector(tag);

const result = await render(Label, { queries: { queryByTag } });

expect(result.queryByTag('text')).not.toBeNull();
expect(result.getByText('initial')).not.toBeNull();
```

## Cleanup

The library destroys the rendered app after each test. To turn that off, set the environment variable `ATL_SKIP_AUTO_CLEANUP=true` and call `cleanup()` or `unmount()` yourself.

## Related

- [Testing](/guide/testing.md): setup, `ng test` and `render()`.
- [Event reference](/api/testing-library/event-reference.md)
- [Testing library API](/api/testing-library/index.md)
- [Handling errors](/guide/error-handling.md#contain-failures-with-boundary)
