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

# Testing

Test your components with `ng test`. `@blotch/angular-lynx-testing-library` renders a component through AngularLynx's real renderer into **jsdom**, a browser-like environment that runs in Node, and gives you [Testing Library](https://testing-library.com/docs/dom-testing-library/intro) queries to check the result.

## Set up

```bash
ng generate @blotch/angular-lynx:add-testing
```

- **What it does.** It installs the testing library, plus Vitest and jsdom if the project doesn't have them. It also makes sure `ng test` runs through the AngularLynx test builder.
- **No config files.** `ng test` loads the library's setup by itself whenever the project has the library. You don't write a Vitest config or a setup file.
- **New components come with a test.** From then on, `ng generate component` adds a `*.test.ts` that renders the component with `render()`.

To install the library by hand instead:

```bash
npm install --save-dev @blotch/angular-lynx-testing-library
```

## Run the tests

```bash
ng test                 # watches for changes in a terminal, runs once in CI
ng test --watch=false   # runs once
```

- **The builder.** `ng add` points the `test` target in `angular.json` at `@blotch/angular-lynx-build:unit-test`. It's Angular's own unit-test builder (Vitest), set up for Lynx, so it takes the same options: `include`, `coverage`, `setupFiles`, `providersFile` and the rest.
- **Test files.** It runs every `*.spec.ts` and `*.test.ts` file. Angular's `TestBed` works too, so the specs that `ng generate service` or `ng generate pipe` writes run as they are. A spec that uses only `TestBed` runs in jsdom, as a web app's does, which has no `EventSource` or `IntersectionObserver`: the runtime gives those to a spec that imports `@blotch/angular-lynx-testing-library`, or the spec stubs them.
- **Strict templates.** Tests compile ahead of time, like the app, and their templates are checked strictly. A component that uses Lynx elements must import `LYNX_ELEMENTS` from `@blotch/angular-lynx`. Generated components already do.

## Render a component

`render()` starts a standalone component the way your app starts, and returns queries bound to what it rendered:

```typescript title="src/app/greeting.test.ts"
import { Component, signal } 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 = signal('World');
}

it('renders a greeting', async () => {
  const { getByText } = await render(Greeting);
  expect(getByText('Hello World')).toBeTruthy();
});
```

- **`render()` is async.** Await it. The first render has finished when it resolves.
- **Lynx elements are real elements in the test.** A `<view>` renders as a `<view>` element and a `<text>` as a `<text>` element, so `querySelector('text')` works.
- **Change detection and the renderer are set up for you.** You don't add `provideRenderer()`, and change detection is zoneless, as in your app.
- **To test a directive on its own**, render it on a Lynx element with `renderDirective()`, as `TestBed.createDirective()` does on the web. See [Test a directive](/guide/testing/patterns.md#test-a-directive).

Pass `providers` to swap in test values for your app's dependencies:

```typescript
import { API_URL } from './api-url';

const { getByText } = await render(Greeting, {
  providers: [{ provide: API_URL, useValue: 'https://api.example.com' }],
});
```

[Testing patterns](/guide/testing/patterns.md#fake-native-apis) uses this to fake native APIs.

Providers every spec needs, such as the app's `provideIcons()`, go in the file the test target names as `providersFile`. `ng test` gives them to every `render()`, as to every `TestBed` test, and a spec's own `providers` override them:

```json title="angular.json"
"test": {
  "builder": "@blotch/angular-lynx-build:unit-test",
  "options": {
    "providersFile": "src/test-providers.ts"
  }
}
```

```typescript title="src/test-providers.ts"
import { provideAppIcons } from './app/icons';

export default [provideAppIcons()];
```

## Query what rendered

Use `getBy*` when the element must exist, and `queryBy*` when it may be absent:

```typescript title="src/app/product-list.test.ts"
import { render, within } from '@blotch/angular-lynx-testing-library';
import { ProductList } from './product-list';

it('lists the products', async () => {
  const { container, getByText, queryByText } = await render(ProductList);

  expect(getByText('Gadget')).toBeTruthy();
  expect(queryByText('Sold out')).toBeNull();

  // Scope queries to one part of the tree with within():
  const secondRow = container.querySelectorAll('view')[1] as HTMLElement;
  expect(within(secondRow).getByText('Gadget')).toBeTruthy();
});
```

The library also exports `screen`, which runs queries against the whole document.

### Find elements as a screen reader does

Lynx elements describe themselves to screen readers with [`accessibility-*` attributes](/guide/accessibility.md), not ARIA. The queries read them:

```typescript title="src/app/favorite.test.ts"
import {
  fireEvent,
  render,
  screen,
  waitForUpdate,
} from '@blotch/angular-lynx-testing-library';
import { Favorite } from './favorite';

it('favorites the item', async () => {
  await render(Favorite);

  fireEvent.tap(screen.getByRole('button', { name: 'Add to favorites' }));
  await waitForUpdate();

  expect(screen.getByAccessibilityLabel('Remove from favorites')).toBeTruthy();
});
```

- **`getByRole`** reads `accessibility-traits`: `button`, `link`, `image` as `img`, `header` as `heading`. The [API reference](/api/testing-library/queries.md#byrole) has the full list.
- **`name`** is the `accessibility-label`, or a `<text>`'s own text.
- **Screen readers must reach the element.** A `<view>` needs `accessibility-element="true"`, so the test fails when people using a screen reader couldn't find the button.
- **`getByAccessibilityLabel`** finds any element by its `accessibility-label`.

`render()` also returns:

- **`container`:** the root `<page>` element that holds everything rendered.
- **`componentRef`:** the component's `ComponentRef`, for reading its instance or its injector.
- **`rerender({ inputs })`:** changes the inputs `render(Component, { inputs })` set, keeping the component. See [Set inputs](/guide/testing/patterns.md#set-inputs).
- **`rerender(Component, options?)`:** renders another component in its place.
- **`asFragment()`:** a copy of the tree, for snapshot tests.
- **`unmount()`:** destroys the app. The library also cleans up after every test by itself.

The [API reference](/api/testing-library/index.md) lists every option and type.

## What jsdom tests can't cover

The tests run your app in jsdom, not on a phone. Some things only exist on a device:

- **Native APIs.** A test has none of your app's native modules, just as Lynx Explorer hasn't. `LynxNativeModule.call()` resolves `undefined`, a native module's methods reject, and `LynxTextMeasure.measure()` throws. `LynxLocalStorage` and `LynxSecureStorage` keep their values in memory. Provide fakes, as in [Fake native APIs](/guide/testing/patterns.md#fake-native-apis).
- **Data from the host app.** No host app runs, so InitData and GlobalData hold nothing unless you provide them. See [Fake host data](/guide/testing/patterns.md#fake-host-data).
- **Background-thread APIs.** The test's background thread answers the calls AngularLynx sends there, but it has few of Lynx's APIs, so a call that needs one it lacks, such as `LynxAccessibility.announce()`, rejects. Your [background functions](/api/main-thread/background-fn.md) run there, so `runOnBackground()` resolves with what the function returns, or rejects with what it throws, as on a device. Like any code on that thread, a background function sees none of your app's native modules. See [Threads](/guide/concepts/threads.md).
- **Main-thread scripts and gestures.** jsdom has no native elements to move, so test dragging and gestures on a device.
- **Layout and native rendering.** jsdom computes no layout, so sizes and positions are unknown, and layout events don't fire by themselves.

Check these by running the app in Lynx Explorer, or on a simulator with [Run on iOS and Android](/guide/native-apps.md).

## Related

- [Testing patterns](/guide/testing/patterns.md): signals, events, snapshots and fakes.
- [Event reference](/api/testing-library/event-reference.md): every event `fireEvent` can send.
- [Testing library API](/api/testing-library/index.md)
