@tarve/test 0.0.0-stage → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +141 -3
- package/package.json +46 -4
- package/src/element.ts +184 -0
- package/src/index.ts +406 -0
- package/src/queries.ts +189 -0
package/README.md
CHANGED
|
@@ -1,3 +1,141 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @tarve/test
|
|
2
|
+
|
|
3
|
+
Testing Library-style tests for Tarve apps. `render` runs your view on
|
|
4
|
+
[`@tarve/headless`](../headless) — the WebAssembly build of Tarve's native tree, with no window,
|
|
5
|
+
GPU or native library — so tests run on any CI machine. Queries read the compiled scene tree
|
|
6
|
+
(what `compileTree` produced and the app sent to the native tree); input goes through native hit
|
|
7
|
+
testing, focus and the app's own event dispatch, exactly as in a window.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
bun add -d @tarve/test @tarve/headless
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```tsx
|
|
14
|
+
import { afterEach, expect, test } from "bun:test";
|
|
15
|
+
import { cleanup, fireEvent, render } from "@tarve/test";
|
|
16
|
+
import { App } from "./app";
|
|
17
|
+
|
|
18
|
+
afterEach(cleanup);
|
|
19
|
+
|
|
20
|
+
test("counts clicks", async () => {
|
|
21
|
+
const view = await render(<App />);
|
|
22
|
+
await fireEvent.click(view.getByRole("button", { name: "Increment" }));
|
|
23
|
+
expect(view.getByTestId("count").text).toBe("Count: 1");
|
|
24
|
+
});
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
`render` is async (it loads the WebAssembly runtime once per process). A view that is not a
|
|
28
|
+
`Window` is wrapped in one, 640×480 unless `width`/`height` say otherwise; `theme` sets its theme.
|
|
29
|
+
Every other `createHeadlessApp` option works (`scale`, `clock`, `fonts`, `assetRoot`, `onError`…).
|
|
30
|
+
|
|
31
|
+
## Queries
|
|
32
|
+
|
|
33
|
+
Every query comes as `getBy*` (one element or throw), `getAllBy*`, `queryBy*` (one or `null`),
|
|
34
|
+
`queryAllBy*`, `findBy*` and `findAllBy*` (wait, like `waitFor`):
|
|
35
|
+
|
|
36
|
+
| Query | Matches |
|
|
37
|
+
|---|---|
|
|
38
|
+
| `ByText(text)` | The text a Text, Button, Markdown or Code shows |
|
|
39
|
+
| `ByRole(role, { name, checked, selected, expanded, disabled })` | `control.role`, or the implicit role: `button`, `textbox` (Input, TextArea), `searchbox` (Input type=search), `slider`, `img`, `window` |
|
|
40
|
+
| `ByLabel(text)` | A control named by `<label htmlFor>`, a `Field` label, a `Label` in a `Field`, or its own `control.label` (Checkbox, Switch, Slider…) |
|
|
41
|
+
| `ByPlaceholder(text)` | An Input or TextArea placeholder |
|
|
42
|
+
| `ByDisplayValue(text)` | The current value of an Input or TextArea |
|
|
43
|
+
| `ByTestId(id)` | The node id: Tarve has no `data-testid`, give the component an `id` |
|
|
44
|
+
|
|
45
|
+
`text` is a string (exact after collapsing whitespace), `{ exact: false }` for a case-insensitive
|
|
46
|
+
substring, a RegExp, or `(content, element) => boolean`. The accessible name is `control.label`,
|
|
47
|
+
then `labelledBy` labels, then a surrounding `Field` label (form controls), then the content of a
|
|
48
|
+
button, link, checkbox, tab… A failed query prints the tree. `within(element)` scopes queries to
|
|
49
|
+
a subtree; `view.debug()` returns the printed tree.
|
|
50
|
+
|
|
51
|
+
Elements (`TestElement`) are live and stable: one object per node id, whose `text`,
|
|
52
|
+
`textContent`, `value`, `name`, `role`, `checked`, `disabled`, `parent`, `children` and `node` (the
|
|
53
|
+
compiled `NativeNode`) always read the current tree. `isConnected` turns false when the node is gone.
|
|
54
|
+
|
|
55
|
+
## Events
|
|
56
|
+
|
|
57
|
+
Every call waits until the app has handled it and re-rendered.
|
|
58
|
+
|
|
59
|
+
| | |
|
|
60
|
+
|---|---|
|
|
61
|
+
| `fireEvent.click(el, { via? })` | Pointer move/down/up at the element's centre (a disabled or covered element gets nothing). `via: "event"` delivers a native `click` to the handler instead |
|
|
62
|
+
| `fireEvent.type(el, text, { clear? })` | Focuses and types; `{Enter}`, `{Tab}`, `{Backspace}`, `{ArrowLeft}`… press keys |
|
|
63
|
+
| `fireEvent.clear(el)` | Select all, delete |
|
|
64
|
+
| `fireEvent.key(key, el?)` | Presses a key, on `el` when given (it gets focus first) |
|
|
65
|
+
| `fireEvent.scroll(el, deltaY \| { deltaX, deltaY })` | Mouse wheel over the element |
|
|
66
|
+
| `fireEvent.hover(el)` | Moves the pointer over it |
|
|
67
|
+
| `fireEvent.native(event)` | Any native event (`{ type: "change", id, value }`…), dispatched like the native tree's |
|
|
68
|
+
|
|
69
|
+
`fireEvent` works with elements of any open render; `view.fireEvent` also takes node ids.
|
|
70
|
+
|
|
71
|
+
## The rest of the render
|
|
72
|
+
|
|
73
|
+
- `rerender(ui?)` re-renders (with `ui` in place of the view, keeping state held in your variables).
|
|
74
|
+
- `unmount()` closes the app; `cleanup()` closes every open render (use it in `afterEach`).
|
|
75
|
+
- `waitFor(callback, { timeout = 1000, interval = 10 })` retries until the callback stops throwing,
|
|
76
|
+
settling every open render before each try. `waitForElementToBeRemoved(() => view.queryByText(…))`.
|
|
77
|
+
- `box(el)` the laid-out box from the native tree; `settle()`; `advance(ms)` moves the manual
|
|
78
|
+
motion clock (transitions, spinners).
|
|
79
|
+
- `app` is the `HeadlessApp` (an `AppHandle`): `inspect()`, `update()`, `capture()`…
|
|
80
|
+
|
|
81
|
+
## Image snapshots
|
|
82
|
+
|
|
83
|
+
`view.snapshot()` returns the current frame as PNG bytes, `view.pixels()` as RGBA.
|
|
84
|
+
|
|
85
|
+
```tsx
|
|
86
|
+
import { toMatchImageSnapshot } from "@tarve/test";
|
|
87
|
+
|
|
88
|
+
await toMatchImageSnapshot(view, `${import.meta.dirname}/__snapshots__/app.png`, { threshold: 8, maxDifferenceRatio: 0.001 });
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
A missing snapshot is written (on CI, where `CI` is set, it fails). A mismatch writes
|
|
92
|
+
`app.actual.png` next to it and throws. `threshold` is the per-channel delta ignored as noise and
|
|
93
|
+
`maxDifferenceRatio` the share of pixels allowed to differ; both default to 0 because captures are
|
|
94
|
+
deterministic (bundled fonts, frozen clock). `TARVE_UPDATE_SNAPSHOTS=1` rewrites stored images.
|
|
95
|
+
As a matcher:
|
|
96
|
+
|
|
97
|
+
```tsx
|
|
98
|
+
import { tarveMatchers } from "@tarve/test";
|
|
99
|
+
expect.extend(tarveMatchers);
|
|
100
|
+
await expect(view).toMatchImageSnapshot("__snapshots__/app.png");
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Test runners and runtimes
|
|
104
|
+
|
|
105
|
+
The package depends on no test runner: queries and events throw plain `Error`s, `waitFor` retries
|
|
106
|
+
on its own timer, and `toMatchImageSnapshot` is a function that throws on a mismatch. Use any
|
|
107
|
+
assertion library; `tarveMatchers` is only an adapter for `expect.extend` (Bun, Jest, Vitest).
|
|
108
|
+
|
|
109
|
+
`node:test` runs unchanged under `bun test` and Node.js, so one file serves both:
|
|
110
|
+
|
|
111
|
+
```tsx
|
|
112
|
+
import { afterEach, test } from "node:test";
|
|
113
|
+
import assert from "node:assert/strict";
|
|
114
|
+
import { cleanup, fireEvent, render } from "@tarve/test";
|
|
115
|
+
|
|
116
|
+
afterEach(cleanup);
|
|
117
|
+
test("counts", async () => {
|
|
118
|
+
const view = await render(<App />);
|
|
119
|
+
await fireEvent.click(view.getByRole("button", { name: "Increment" }));
|
|
120
|
+
assert.equal(view.getByTestId("count").text, "Count: 1");
|
|
121
|
+
});
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
| Runtime | Run | |
|
|
125
|
+
|---|---|---|
|
|
126
|
+
| Bun 1.4+ | `bun test` | Everything |
|
|
127
|
+
| Node.js 26.10+ | `tarve run --runtime node app.test.tsx` (bundles the TSX and the WebAssembly/font files, then runs `node`, which runs the `node:test` tests and exits non-zero on a failure) | Everything |
|
|
128
|
+
| txiki.js 26.6 | `tarve build --runtime txiki app.test.tsx`, run the executable | Everything, but no test runner and no `node:assert`: call your tests from a plain script and throw on failure |
|
|
129
|
+
|
|
130
|
+
See [@tarve/headless](../headless#runtimes). In this repository `bun run smoke:headless-runtimes`
|
|
131
|
+
runs the scenarios in `smoke/scenarios.tsx` on all three runtimes (`node --test` for Node.js).
|
|
132
|
+
|
|
133
|
+
## Limits
|
|
134
|
+
|
|
135
|
+
- No window: dialogs, clipboard, tray, notifications and the OS accessibility tree are desktop-only.
|
|
136
|
+
Roles come from Tarve's `control` metadata, not from a platform accessibility API.
|
|
137
|
+
- Queries see the whole compiled tree, including nodes scrolled out of view or clipped; use
|
|
138
|
+
`box(el)` to check what is laid out. Pointer events need the element laid out with a size.
|
|
139
|
+
- `onKeyDown` only receives the keys the native tree reports (menus, selects, tree items);
|
|
140
|
+
editing keys go to the focused field.
|
|
141
|
+
- `render` is async and `rerender` returns a promise, unlike React Testing Library.
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tarve/test",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.10.0",
|
|
4
|
+
"description": "Testing Library-style queries, events and image snapshots for Tarve apps, rendered headless on any platform",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"tarve",
|
|
8
|
+
"testing",
|
|
9
|
+
"testing-library",
|
|
10
|
+
"headless",
|
|
11
|
+
"snapshot",
|
|
12
|
+
"visual-regression"
|
|
13
|
+
],
|
|
14
|
+
"homepage": "https://github.com/omarcosr/tarve/tree/main/packages/test#readme",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/omarcosr/tarve.git",
|
|
18
|
+
"directory": "packages/test"
|
|
19
|
+
},
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/omarcosr/tarve/issues"
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public",
|
|
25
|
+
"provenance": true
|
|
26
|
+
},
|
|
27
|
+
"type": "module",
|
|
28
|
+
"exports": {
|
|
29
|
+
".": "./src/index.ts"
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"src",
|
|
33
|
+
"!src/**/*.test.tsx",
|
|
34
|
+
"README.md"
|
|
35
|
+
],
|
|
36
|
+
"scripts": {
|
|
37
|
+
"test": "bun test",
|
|
38
|
+
"smoke:runtimes": "bun ../../scripts/smoke-headless-runtimes.ts"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"@tarve/core": "^0.10.0",
|
|
42
|
+
"@tarve/headless": "^0.10.0"
|
|
43
|
+
},
|
|
44
|
+
"engines": {
|
|
45
|
+
"bun": ">=1.4.0",
|
|
46
|
+
"node": ">=26.10.0"
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/element.ts
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import type { SceneNode } from "@tarve/headless";
|
|
2
|
+
|
|
3
|
+
/** A node role: the `control.role` a component declared, or the implicit role of its kind. */
|
|
4
|
+
export type Role = NonNullable<SceneNode["control"]>["role"] | "textbox" | "searchbox" | "img" | "window" | (string & {});
|
|
5
|
+
|
|
6
|
+
/** What a `TestElement` reads its live node from: one rendered app. */
|
|
7
|
+
export interface ElementHost {
|
|
8
|
+
node(id: string): SceneNode | undefined;
|
|
9
|
+
parentId(id: string): string | undefined;
|
|
10
|
+
childIds(id: string): readonly string[];
|
|
11
|
+
element(id: string): TestElement;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Kinds whose `text` is what a user reads. Inputs show a value instead (`getByDisplayValue`). */
|
|
15
|
+
const TEXT_KINDS = new Set(["text", "button", "markdown", "code", "titlebar"]);
|
|
16
|
+
/** Roles named from their content when they have no label, as in ARIA. */
|
|
17
|
+
const NAME_FROM_CONTENT = new Set(["button", "link", "checkbox", "switch", "radio", "tab", "menuitem", "treeitem", "option", "toggle", "row", "label", "alert", "status"]);
|
|
18
|
+
/** Roles a `Field`'s label names. */
|
|
19
|
+
export const FORM_ROLES = new Set(["textbox", "searchbox", "slider", "checkbox", "switch", "radio", "radiogroup", "select", "toggle", "togglegroup", "otpSlot"]);
|
|
20
|
+
|
|
21
|
+
export function normalize(text: string): string {
|
|
22
|
+
return text.replace(/\s+/g, " ").trim();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The role of a scene node: its `control.role`, else the implicit role of its kind. */
|
|
26
|
+
export function roleOf(node: SceneNode): Role | undefined {
|
|
27
|
+
if (node.control?.role) return node.control.role;
|
|
28
|
+
switch (node.kind) {
|
|
29
|
+
case "button":
|
|
30
|
+
return "button";
|
|
31
|
+
case "input":
|
|
32
|
+
return node.inputType === "search" ? "searchbox" : "textbox";
|
|
33
|
+
case "textarea":
|
|
34
|
+
return "textbox";
|
|
35
|
+
case "slider":
|
|
36
|
+
return "slider";
|
|
37
|
+
case "image":
|
|
38
|
+
case "svg":
|
|
39
|
+
return "img";
|
|
40
|
+
case "window":
|
|
41
|
+
return "window";
|
|
42
|
+
default:
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The text a node shows itself (not its children's). */
|
|
48
|
+
export function ownText(node: SceneNode): string {
|
|
49
|
+
if (TEXT_KINDS.has(node.kind)) return node.text ?? node.source ?? "";
|
|
50
|
+
return "";
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* One node of the rendered scene tree. It is live: its properties read the current tree, so
|
|
55
|
+
* after an event or a re-render they show the new text, value or state. Reading a removed
|
|
56
|
+
* element throws (check `isConnected`).
|
|
57
|
+
*/
|
|
58
|
+
export class TestElement {
|
|
59
|
+
constructor(
|
|
60
|
+
private readonly host: ElementHost,
|
|
61
|
+
/** The node id: the `id` prop when the component set one, else a generated path. */
|
|
62
|
+
readonly id: string,
|
|
63
|
+
) {}
|
|
64
|
+
|
|
65
|
+
/** The node as the app compiled it (`compileTree`), without children. */
|
|
66
|
+
get node(): SceneNode {
|
|
67
|
+
const node = this.host.node(this.id);
|
|
68
|
+
if (!node) throw new Error(`Element #${this.id} is no longer in the tree`);
|
|
69
|
+
return node;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
get isConnected(): boolean {
|
|
73
|
+
return this.host.node(this.id) !== undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Native kind: `text`, `button`, `input`, `view`, `pressable`… */
|
|
77
|
+
get kind(): string {
|
|
78
|
+
return this.node.kind;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
get role(): Role | undefined {
|
|
82
|
+
return roleOf(this.node);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The accessible name, as `getByRole(role, { name })` matches it. */
|
|
86
|
+
get name(): string {
|
|
87
|
+
const node = this.node;
|
|
88
|
+
if (node.control?.label) return normalize(node.control.label);
|
|
89
|
+
if (node.labelledBy?.length) {
|
|
90
|
+
return normalize(node.labelledBy.map((id) => (this.host.node(id) ? this.host.element(id).textContent : "")).join(" "));
|
|
91
|
+
}
|
|
92
|
+
const role = this.role;
|
|
93
|
+
if (role && FORM_ROLES.has(role)) {
|
|
94
|
+
const field = this.closest((element) => element.node.control?.role === "field");
|
|
95
|
+
if (field?.node.control?.label) return normalize(field.node.control.label);
|
|
96
|
+
}
|
|
97
|
+
if (role && NAME_FROM_CONTENT.has(role)) return this.textContent;
|
|
98
|
+
if (node.kind === "input" || node.kind === "textarea") return normalize(node.placeholder ?? "");
|
|
99
|
+
return normalize(ownText(node));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The node's own text: a Text, Button or Markdown source. Empty for containers and inputs. */
|
|
103
|
+
get text(): string {
|
|
104
|
+
return normalize(ownText(this.node));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The text of the node and every descendant, joined with spaces. */
|
|
108
|
+
get textContent(): string {
|
|
109
|
+
const parts: string[] = [];
|
|
110
|
+
const walk = (id: string) => {
|
|
111
|
+
const node = this.host.node(id);
|
|
112
|
+
if (!node) return;
|
|
113
|
+
const text = ownText(node);
|
|
114
|
+
if (text) parts.push(text);
|
|
115
|
+
for (const child of this.host.childIds(id)) walk(child);
|
|
116
|
+
};
|
|
117
|
+
walk(this.id);
|
|
118
|
+
return normalize(parts.join(" "));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** The value of an Input or TextArea. */
|
|
122
|
+
get value(): string | undefined {
|
|
123
|
+
return this.node.value;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
get placeholder(): string | undefined {
|
|
127
|
+
return this.node.placeholder;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
get disabled(): boolean {
|
|
131
|
+
return this.node.disabled === true;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
get checked(): boolean | undefined {
|
|
135
|
+
return this.node.control?.checked;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
get selected(): boolean | undefined {
|
|
139
|
+
return this.node.control?.selected;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
get expanded(): boolean | undefined {
|
|
143
|
+
return this.node.control?.expanded;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
get parent(): TestElement | undefined {
|
|
147
|
+
const id = this.host.parentId(this.id);
|
|
148
|
+
return id === undefined ? undefined : this.host.element(id);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
get children(): TestElement[] {
|
|
152
|
+
return this.host.childIds(this.id).map((id) => this.host.element(id));
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** This element and its ancestors, nearest first, until one matches. */
|
|
156
|
+
closest(predicate: (element: TestElement) => boolean): TestElement | undefined {
|
|
157
|
+
for (let element: TestElement | undefined = this; element; element = element.parent) {
|
|
158
|
+
if (predicate(element)) return element;
|
|
159
|
+
}
|
|
160
|
+
return undefined;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Every descendant in document order. */
|
|
164
|
+
descendants(): TestElement[] {
|
|
165
|
+
const out: TestElement[] = [];
|
|
166
|
+
const walk = (id: string) => {
|
|
167
|
+
for (const child of this.host.childIds(id)) {
|
|
168
|
+
out.push(this.host.element(child));
|
|
169
|
+
walk(child);
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
walk(this.id);
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
toString(): string {
|
|
177
|
+
if (!this.isConnected) return `<removed #${this.id}>`;
|
|
178
|
+
const role = this.role ? ` role=${JSON.stringify(this.role)}` : "";
|
|
179
|
+
const name = this.role && this.name ? ` name=${JSON.stringify(this.name)}` : "";
|
|
180
|
+
const text = this.text ? ` ${JSON.stringify(this.text)}` : "";
|
|
181
|
+
const value = this.value !== undefined ? ` value=${JSON.stringify(this.value)}` : "";
|
|
182
|
+
return `<${this.kind}#${this.id}${role}${name}${value}>${text}`;
|
|
183
|
+
}
|
|
184
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
import { Window, type AppOptions, type PixelComparison, type RgbaImage, type ThemeDefinition, type VNode } from "@tarve/core";
|
|
2
|
+
import { jsx } from "@tarve/core/jsx-runtime";
|
|
3
|
+
import {
|
|
4
|
+
createHeadlessApp,
|
|
5
|
+
matchImageSnapshot,
|
|
6
|
+
type HeadlessApp,
|
|
7
|
+
type HeadlessBridge,
|
|
8
|
+
type HeadlessBridgeOptions,
|
|
9
|
+
type HeadlessRuntimeOptions,
|
|
10
|
+
type ImageSnapshotOptions,
|
|
11
|
+
type SceneNode,
|
|
12
|
+
} from "@tarve/headless";
|
|
13
|
+
import { TestElement, type ElementHost } from "./element";
|
|
14
|
+
import { bindQueries, type Queries, type WaitForOptions } from "./queries";
|
|
15
|
+
|
|
16
|
+
export { TestElement, roleOf, type Role } from "./element";
|
|
17
|
+
export type { Matcher, MatcherOptions, Queries, RoleOptions, WaitForOptions } from "./queries";
|
|
18
|
+
export type { SceneNode } from "@tarve/headless";
|
|
19
|
+
|
|
20
|
+
type NativeEvent = Parameters<HeadlessBridge["emit"]>[0];
|
|
21
|
+
type NodeBox = Awaited<ReturnType<HeadlessApp["inspect"]>>["nodes"][number];
|
|
22
|
+
|
|
23
|
+
export interface RenderOptions extends Omit<AppOptions, "bridge" | "debug" | "headless">, HeadlessBridgeOptions, HeadlessRuntimeOptions {
|
|
24
|
+
/** Theme of the Window wrapped around a view that is not a Window. */
|
|
25
|
+
theme?: ThemeDefinition;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Where an event goes: an element, or a node id in the render. */
|
|
29
|
+
export type Target = TestElement | string;
|
|
30
|
+
|
|
31
|
+
export interface ClickOptions {
|
|
32
|
+
/**
|
|
33
|
+
* `pointer` (default): move, press and release at the element's centre, through native hit
|
|
34
|
+
* testing, like a user (a disabled or covered element does not get the click). `event`:
|
|
35
|
+
* deliver a `click` event for the node straight to the app's handler dispatch.
|
|
36
|
+
*/
|
|
37
|
+
via?: "pointer" | "event";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface TypeOptions {
|
|
41
|
+
/** Select everything and delete it first. */
|
|
42
|
+
clear?: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface ScrollOptions {
|
|
46
|
+
delta?: number;
|
|
47
|
+
deltaX?: number;
|
|
48
|
+
deltaY?: number;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Input for one render. Every call waits until the app has re-rendered (`settle`). */
|
|
52
|
+
export interface FireEvent {
|
|
53
|
+
click(target: Target, options?: ClickOptions): Promise<void>;
|
|
54
|
+
/** Moves the pointer over the element's centre. */
|
|
55
|
+
hover(target: Target): Promise<void>;
|
|
56
|
+
/** Focuses the element and types `text`. `{Enter}`, `{Tab}`, `{Backspace}`… inside it press keys. */
|
|
57
|
+
type(target: Target, text: string, options?: TypeOptions): Promise<void>;
|
|
58
|
+
/** Selects everything in a field and deletes it. */
|
|
59
|
+
clear(target: Target): Promise<void>;
|
|
60
|
+
/** Presses a key (`Enter`, `Escape`, `Tab`, `ArrowDown`, `Backspace`, `SelectAll`…), on `target` when given (it gets focus). */
|
|
61
|
+
key(key: string, target?: Target): Promise<void>;
|
|
62
|
+
/** Wheels over the element's centre: a number is the vertical delta in pixels. */
|
|
63
|
+
scroll(target: Target, options: number | ScrollOptions): Promise<void>;
|
|
64
|
+
/** Delivers a native event to the app as the native tree would (`{ type: "change", id, value }`…). */
|
|
65
|
+
native(event: NativeEvent): Promise<void>;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export interface RenderResult extends Queries {
|
|
69
|
+
readonly app: HeadlessApp;
|
|
70
|
+
/** The root element: the Window. */
|
|
71
|
+
readonly container: TestElement;
|
|
72
|
+
readonly fireEvent: FireEvent;
|
|
73
|
+
/** The compiled scene tree as the app last sent it (no layout). */
|
|
74
|
+
scene(): SceneNode;
|
|
75
|
+
/** The element with this node id, or undefined. */
|
|
76
|
+
element(id: string): TestElement | undefined;
|
|
77
|
+
/** Every element in document order. */
|
|
78
|
+
elements(): TestElement[];
|
|
79
|
+
/** The tree as indented text, as printed under a failed query. */
|
|
80
|
+
debug(): string;
|
|
81
|
+
/** Renders again: the same view, or `ui` in its place. Component state in your own variables stays. */
|
|
82
|
+
rerender(ui?: VNode | (() => VNode)): Promise<void>;
|
|
83
|
+
/** Closes the app. `cleanup()` unmounts every render still open. */
|
|
84
|
+
unmount(): void;
|
|
85
|
+
/** Waits until layout feedback and re-renders stop. */
|
|
86
|
+
settle(): Promise<void>;
|
|
87
|
+
/** Layout box of an element from the native tree, or undefined when it is not laid out. */
|
|
88
|
+
box(target: Target): Promise<NodeBox | undefined>;
|
|
89
|
+
/** The current frame as PNG bytes. */
|
|
90
|
+
snapshot(): Uint8Array;
|
|
91
|
+
/** The current frame as RGBA pixels. */
|
|
92
|
+
pixels(): RgbaImage;
|
|
93
|
+
/** Advances the manual motion clock (transitions, spinners) and settles. */
|
|
94
|
+
advance(milliseconds: number): Promise<void>;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const mounted = new Set<RenderResult>();
|
|
98
|
+
const owners = new WeakMap<TestElement, RenderResult>();
|
|
99
|
+
|
|
100
|
+
function asView(ui: VNode | (() => VNode)): () => VNode {
|
|
101
|
+
return typeof ui === "function" ? ui : () => ui;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
interface Indexed {
|
|
105
|
+
version: number;
|
|
106
|
+
nodes: Map<string, SceneNode>;
|
|
107
|
+
parents: Map<string, string | undefined>;
|
|
108
|
+
children: Map<string, string[]>;
|
|
109
|
+
order: string[];
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function indexScene(root: SceneNode | undefined, version: number): Indexed {
|
|
113
|
+
const index: Indexed = { version, nodes: new Map(), parents: new Map(), children: new Map(), order: [] };
|
|
114
|
+
const walk = (node: SceneNode, parent: string | undefined) => {
|
|
115
|
+
index.nodes.set(node.id, node);
|
|
116
|
+
index.parents.set(node.id, parent);
|
|
117
|
+
index.children.set(node.id, node.children.map((child) => child.id));
|
|
118
|
+
index.order.push(node.id);
|
|
119
|
+
for (const child of node.children) walk(child, node.id);
|
|
120
|
+
};
|
|
121
|
+
if (root) walk(root, undefined);
|
|
122
|
+
return index;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Retries `callback` until it stops throwing (and settles every open render before each try), then
|
|
129
|
+
* returns its value. Throws its last error after `timeout` ms.
|
|
130
|
+
*/
|
|
131
|
+
export async function waitFor<T>(callback: () => T | Promise<T>, options: WaitForOptions = {}): Promise<T> {
|
|
132
|
+
const timeout = options.timeout ?? 1000;
|
|
133
|
+
const interval = options.interval ?? 10;
|
|
134
|
+
const deadline = performance.now() + timeout;
|
|
135
|
+
for (;;) {
|
|
136
|
+
await Promise.all([...mounted].map((result) => result.settle()));
|
|
137
|
+
try {
|
|
138
|
+
return await callback();
|
|
139
|
+
} catch (error) {
|
|
140
|
+
if (performance.now() >= deadline) {
|
|
141
|
+
if (error instanceof Error) error.message = `waitFor timed out after ${timeout}ms: ${error.message}`;
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
await sleep(interval);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Waits until `callback` throws or returns `null`/`undefined`/`false`/an empty array: the element went away. */
|
|
150
|
+
export async function waitForElementToBeRemoved(callback: () => unknown, options?: WaitForOptions): Promise<void> {
|
|
151
|
+
await waitFor(() => {
|
|
152
|
+
let value: unknown;
|
|
153
|
+
try {
|
|
154
|
+
value = callback();
|
|
155
|
+
} catch {
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (value instanceof TestElement && !value.isConnected) return;
|
|
159
|
+
if (value === null || value === undefined || value === false || (Array.isArray(value) && value.length === 0)) return;
|
|
160
|
+
throw new Error(`Still present: ${String(value)}`);
|
|
161
|
+
}, options);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const KEY_TOKEN = /\{([^{}]+)\}/g;
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Renders `ui` on the headless WebAssembly runtime (no window, no GPU) and returns queries over
|
|
168
|
+
* its compiled scene tree, input that goes through the same native event dispatch as a window,
|
|
169
|
+
* and pixel snapshots. A view that is not a `Window` is wrapped in one (640×480 by default).
|
|
170
|
+
*/
|
|
171
|
+
export async function render(ui: VNode | (() => VNode), options: RenderOptions = {}): Promise<RenderResult> {
|
|
172
|
+
const { theme, ...appOptions } = options;
|
|
173
|
+
let view = asView(ui);
|
|
174
|
+
const root = () => {
|
|
175
|
+
const node = view();
|
|
176
|
+
if (node.type === Window) return node;
|
|
177
|
+
return jsx(Window, { width: options.width ?? 640, height: options.height ?? 480, ...(theme ? { theme } : {}), children: node });
|
|
178
|
+
};
|
|
179
|
+
const app = await createHeadlessApp(root, appOptions);
|
|
180
|
+
const bridge = app.bridge;
|
|
181
|
+
let index = indexScene(bridge.scene(), bridge.sceneVersion);
|
|
182
|
+
let closed = false;
|
|
183
|
+
const elementCache = new Map<string, TestElement>();
|
|
184
|
+
|
|
185
|
+
const current = (): Indexed => {
|
|
186
|
+
if (index.version !== bridge.sceneVersion) index = indexScene(bridge.scene(), bridge.sceneVersion);
|
|
187
|
+
return index;
|
|
188
|
+
};
|
|
189
|
+
const host: ElementHost = {
|
|
190
|
+
node: (id) => current().nodes.get(id),
|
|
191
|
+
parentId: (id) => current().parents.get(id),
|
|
192
|
+
childIds: (id) => current().children.get(id) ?? [],
|
|
193
|
+
element: (id) => {
|
|
194
|
+
let element = elementCache.get(id);
|
|
195
|
+
if (!element) {
|
|
196
|
+
elementCache.set(id, (element = new TestElement(host, id)));
|
|
197
|
+
owners.set(element, result);
|
|
198
|
+
}
|
|
199
|
+
return element;
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
const elements = () => current().order.map((id) => host.element(id));
|
|
203
|
+
const debug = () => printTree(elements()[0]);
|
|
204
|
+
const settle = async () => {
|
|
205
|
+
if (!closed) await app.settle();
|
|
206
|
+
};
|
|
207
|
+
const resolve = (target: Target): TestElement => {
|
|
208
|
+
if (typeof target !== "string") return target;
|
|
209
|
+
if (!current().nodes.has(target)) throw new Error(`No node with id ${JSON.stringify(target)}\n\n${debug()}`);
|
|
210
|
+
return host.element(target);
|
|
211
|
+
};
|
|
212
|
+
const box = async (target: Target) => {
|
|
213
|
+
const id = resolve(target).id;
|
|
214
|
+
return (await app.inspect()).nodes.find((node) => node.id === id);
|
|
215
|
+
};
|
|
216
|
+
const centre = async (target: Target) => {
|
|
217
|
+
const found = await box(target);
|
|
218
|
+
if (!found || found.width <= 0 || found.height <= 0) return undefined;
|
|
219
|
+
return { x: found.x + found.width / 2, y: found.y + found.height / 2 };
|
|
220
|
+
};
|
|
221
|
+
const input = (command: Parameters<HeadlessApp["debug"]>[0]) => app.debug(command);
|
|
222
|
+
const typeText = (text: string) => {
|
|
223
|
+
let last = 0;
|
|
224
|
+
for (const match of text.matchAll(KEY_TOKEN)) {
|
|
225
|
+
if (match.index > last) input({ type: "input", action: "text", text: text.slice(last, match.index) });
|
|
226
|
+
input({ type: "input", action: "key", text: match[1]! });
|
|
227
|
+
last = match.index + match[0].length;
|
|
228
|
+
}
|
|
229
|
+
if (last < text.length) input({ type: "input", action: "text", text: text.slice(last) });
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
const fireEvent: FireEvent = {
|
|
233
|
+
async click(target, clickOptions = {}) {
|
|
234
|
+
const element = resolve(target);
|
|
235
|
+
const point = clickOptions.via === "event" ? undefined : await centre(element);
|
|
236
|
+
if (point) {
|
|
237
|
+
input({ type: "input", action: "move", ...point });
|
|
238
|
+
input({ type: "input", action: "down" });
|
|
239
|
+
input({ type: "input", action: "up" });
|
|
240
|
+
} else {
|
|
241
|
+
if (clickOptions.via !== "event" && element.disabled) throw new Error(`${element} is disabled and not laid out`);
|
|
242
|
+
bridge.emit({ type: "click", id: element.id });
|
|
243
|
+
}
|
|
244
|
+
await settle();
|
|
245
|
+
},
|
|
246
|
+
async hover(target) {
|
|
247
|
+
const point = await centre(target);
|
|
248
|
+
if (!point) throw new Error(`${resolve(target)} is not laid out: nothing to hover`);
|
|
249
|
+
input({ type: "input", action: "move", ...point });
|
|
250
|
+
await settle();
|
|
251
|
+
},
|
|
252
|
+
async type(target, text, typeOptions = {}) {
|
|
253
|
+
const element = resolve(target);
|
|
254
|
+
app.focus(element.id);
|
|
255
|
+
if (typeOptions.clear) {
|
|
256
|
+
input({ type: "input", action: "key", text: "SelectAll" });
|
|
257
|
+
input({ type: "input", action: "key", text: "Backspace" });
|
|
258
|
+
}
|
|
259
|
+
typeText(text);
|
|
260
|
+
await settle();
|
|
261
|
+
},
|
|
262
|
+
async clear(target) {
|
|
263
|
+
app.focus(resolve(target).id);
|
|
264
|
+
input({ type: "input", action: "key", text: "SelectAll" });
|
|
265
|
+
input({ type: "input", action: "key", text: "Backspace" });
|
|
266
|
+
await settle();
|
|
267
|
+
},
|
|
268
|
+
async key(key, target) {
|
|
269
|
+
if (!key) throw new TypeError("fireEvent.key needs a key");
|
|
270
|
+
if (target !== undefined) app.focus(resolve(target).id);
|
|
271
|
+
input({ type: "input", action: "key", text: key });
|
|
272
|
+
await settle();
|
|
273
|
+
},
|
|
274
|
+
async scroll(target, scrollOptions) {
|
|
275
|
+
const point = await centre(target);
|
|
276
|
+
if (!point) throw new Error(`${resolve(target)} is not laid out: nothing to scroll`);
|
|
277
|
+
const wheel = typeof scrollOptions === "number" ? { deltaY: scrollOptions } : scrollOptions;
|
|
278
|
+
input({ type: "input", action: "move", ...point });
|
|
279
|
+
input({ type: "input", action: "wheel", ...wheel });
|
|
280
|
+
await settle();
|
|
281
|
+
},
|
|
282
|
+
async native(event) {
|
|
283
|
+
bridge.emit(event);
|
|
284
|
+
await settle();
|
|
285
|
+
},
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
const queries = bindQueries({ elements, debug, waitFor });
|
|
289
|
+
const result: RenderResult = {
|
|
290
|
+
...queries,
|
|
291
|
+
app,
|
|
292
|
+
get container() {
|
|
293
|
+
return host.element(current().order[0]!);
|
|
294
|
+
},
|
|
295
|
+
fireEvent,
|
|
296
|
+
scene: () => {
|
|
297
|
+
const scene = bridge.scene();
|
|
298
|
+
if (!scene) throw new Error("The app has not rendered");
|
|
299
|
+
return scene;
|
|
300
|
+
},
|
|
301
|
+
element: (id) => (current().nodes.has(id) ? host.element(id) : undefined),
|
|
302
|
+
elements,
|
|
303
|
+
debug,
|
|
304
|
+
async rerender(next) {
|
|
305
|
+
if (next !== undefined) view = asView(next);
|
|
306
|
+
app.update();
|
|
307
|
+
app.flush();
|
|
308
|
+
await settle();
|
|
309
|
+
},
|
|
310
|
+
unmount() {
|
|
311
|
+
if (closed) return;
|
|
312
|
+
closed = true;
|
|
313
|
+
mounted.delete(result);
|
|
314
|
+
app.close();
|
|
315
|
+
},
|
|
316
|
+
settle,
|
|
317
|
+
box,
|
|
318
|
+
snapshot: () => app.png(),
|
|
319
|
+
pixels: () => app.pixels(),
|
|
320
|
+
async advance(milliseconds) {
|
|
321
|
+
await app.advanceMotion(milliseconds);
|
|
322
|
+
await settle();
|
|
323
|
+
},
|
|
324
|
+
};
|
|
325
|
+
mounted.add(result);
|
|
326
|
+
return result;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** Queries limited to an element and its descendants. */
|
|
330
|
+
export function within(element: TestElement): Queries {
|
|
331
|
+
return bindQueries({
|
|
332
|
+
elements: () => (element.isConnected ? [element, ...element.descendants()] : []),
|
|
333
|
+
debug: () => (element.isConnected ? printTree(element) : String(element)),
|
|
334
|
+
waitFor,
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function ownerOf(target: Target): RenderResult {
|
|
339
|
+
const owner = typeof target === "string" ? [...mounted].at(-1) : owners.get(target);
|
|
340
|
+
if (!owner) throw new Error("fireEvent: the element does not belong to an open render");
|
|
341
|
+
return owner;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** Input on the render an element belongs to (a string id targets the latest render). */
|
|
345
|
+
export const fireEvent: FireEvent = {
|
|
346
|
+
click: (target, options) => ownerOf(target).fireEvent.click(target, options),
|
|
347
|
+
hover: (target) => ownerOf(target).fireEvent.hover(target),
|
|
348
|
+
type: (target, text, options) => ownerOf(target).fireEvent.type(target, text, options),
|
|
349
|
+
clear: (target) => ownerOf(target).fireEvent.clear(target),
|
|
350
|
+
key: (key, target) => (target === undefined ? latest() : ownerOf(target)).fireEvent.key(key, target),
|
|
351
|
+
scroll: (target, options) => ownerOf(target).fireEvent.scroll(target, options),
|
|
352
|
+
native: (event) => latest().fireEvent.native(event),
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
function latest(): RenderResult {
|
|
356
|
+
const last = [...mounted].at(-1);
|
|
357
|
+
if (!last) throw new Error("fireEvent: nothing is rendered");
|
|
358
|
+
return last;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/** Unmounts every render still open. Call it in `afterEach`. */
|
|
362
|
+
export function cleanup(): void {
|
|
363
|
+
for (const result of [...mounted]) result.unmount();
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** The tree under `element` as indented text. */
|
|
367
|
+
export function printTree(element: TestElement | undefined, maxLines = 200): string {
|
|
368
|
+
if (!element) return "(empty tree)";
|
|
369
|
+
const lines: string[] = [];
|
|
370
|
+
const walk = (current: TestElement, depth: number) => {
|
|
371
|
+
if (lines.length >= maxLines) return;
|
|
372
|
+
lines.push(`${" ".repeat(depth)}${current}`);
|
|
373
|
+
for (const child of current.children) walk(child, depth + 1);
|
|
374
|
+
};
|
|
375
|
+
walk(element, 0);
|
|
376
|
+
if (lines.length >= maxLines) lines.push("…");
|
|
377
|
+
return lines.join("\n");
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
export interface MatchImageOptions extends ImageSnapshotOptions {}
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Compares the render's current frame (or an image) with the PNG at `file`. A missing file is
|
|
384
|
+
* written (on CI it fails); a mismatch past `maxDifferenceRatio` (share of pixels, default 0)
|
|
385
|
+
* — counting only channel deltas above `threshold` — writes `<file>.actual.png` and throws.
|
|
386
|
+
* `TARVE_UPDATE_SNAPSHOTS=1` rewrites the stored images.
|
|
387
|
+
*/
|
|
388
|
+
export async function toMatchImageSnapshot(source: RenderResult | RgbaImage, file: string, options: MatchImageOptions = {}): Promise<PixelComparison | undefined> {
|
|
389
|
+
if ("settle" in source) await source.settle();
|
|
390
|
+
const image = "pixels" in source && typeof source.pixels === "function" ? source.pixels() : (source as RgbaImage);
|
|
391
|
+
return matchImageSnapshot(image, file, options);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Matchers for `expect.extend(tarveMatchers)`: `await expect(view).toMatchImageSnapshot(file, options)`.
|
|
396
|
+
*/
|
|
397
|
+
export const tarveMatchers = {
|
|
398
|
+
async toMatchImageSnapshot(received: unknown, file: string, options?: MatchImageOptions) {
|
|
399
|
+
try {
|
|
400
|
+
await toMatchImageSnapshot(received as RenderResult | RgbaImage, file, options);
|
|
401
|
+
return { pass: true, message: () => `expected the image not to match ${file}` };
|
|
402
|
+
} catch (error) {
|
|
403
|
+
return { pass: false, message: () => (error instanceof Error ? error.message : String(error)) };
|
|
404
|
+
}
|
|
405
|
+
},
|
|
406
|
+
};
|
package/src/queries.ts
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { FORM_ROLES, normalize, type Role, type TestElement } from "./element";
|
|
2
|
+
|
|
3
|
+
/** Text to find: exact (after collapsing whitespace), a RegExp, or a predicate. */
|
|
4
|
+
export type Matcher = string | RegExp | ((content: string, element: TestElement) => boolean);
|
|
5
|
+
|
|
6
|
+
export interface MatcherOptions {
|
|
7
|
+
/** `false`: a string matches a case-insensitive substring. Default `true`. */
|
|
8
|
+
exact?: boolean;
|
|
9
|
+
/** Replaces the default whitespace collapsing. */
|
|
10
|
+
normalizer?: (text: string) => string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface RoleOptions extends MatcherOptions {
|
|
14
|
+
/** Accessible name: `control.label`, a `<label htmlFor>`, a `Field` label, or the content of a button/link. */
|
|
15
|
+
name?: Matcher;
|
|
16
|
+
checked?: boolean;
|
|
17
|
+
selected?: boolean;
|
|
18
|
+
expanded?: boolean;
|
|
19
|
+
disabled?: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface WaitForOptions {
|
|
23
|
+
/** Milliseconds before giving up. Default 1000. */
|
|
24
|
+
timeout?: number;
|
|
25
|
+
/** Milliseconds between attempts. Default 10. */
|
|
26
|
+
interval?: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function matches(content: string, element: TestElement, matcher: Matcher, options: MatcherOptions = {}): boolean {
|
|
30
|
+
const text = (options.normalizer ?? normalize)(content);
|
|
31
|
+
if (typeof matcher === "function") return matcher(text, element);
|
|
32
|
+
if (matcher instanceof RegExp) {
|
|
33
|
+
matcher.lastIndex = 0;
|
|
34
|
+
return matcher.test(text);
|
|
35
|
+
}
|
|
36
|
+
if (options.exact === false) return text.toLowerCase().includes(normalize(matcher).toLowerCase());
|
|
37
|
+
return text === normalize(matcher);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const describeMatcher = (matcher: Matcher) => (typeof matcher === "function" ? "a predicate" : typeof matcher === "string" ? JSON.stringify(matcher) : String(matcher));
|
|
41
|
+
|
|
42
|
+
/** Roles whose own label is the thing a user reads next to a form control. */
|
|
43
|
+
const LABEL_ONLY = new Set(["label", "field", "group", "alert", "status", "navigation", "tablist", "radiogroup", "togglegroup"]);
|
|
44
|
+
|
|
45
|
+
type Finder<M, O> = (elements: readonly TestElement[], matcher: M, options?: O) => TestElement[];
|
|
46
|
+
|
|
47
|
+
interface QueryKind<M, O> {
|
|
48
|
+
find: Finder<M, O>;
|
|
49
|
+
describe(matcher: M, options?: O): string;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const byText: QueryKind<Matcher, MatcherOptions> = {
|
|
53
|
+
find: (elements, matcher, options) => elements.filter((element) => element.text !== "" && matches(element.text, element, matcher, options)),
|
|
54
|
+
describe: (matcher) => `text ${describeMatcher(matcher)}`,
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const byRole: QueryKind<Role, RoleOptions> = {
|
|
58
|
+
find: (elements, role, options = {}) =>
|
|
59
|
+
elements.filter((element) => {
|
|
60
|
+
if (element.role !== role) return false;
|
|
61
|
+
if (options.checked !== undefined && element.checked !== options.checked) return false;
|
|
62
|
+
if (options.selected !== undefined && element.selected !== options.selected) return false;
|
|
63
|
+
if (options.expanded !== undefined && element.expanded !== options.expanded) return false;
|
|
64
|
+
if (options.disabled !== undefined && element.disabled !== options.disabled) return false;
|
|
65
|
+
return options.name === undefined || matches(element.name, element, options.name, options);
|
|
66
|
+
}),
|
|
67
|
+
describe: (role, options = {}) => `role ${JSON.stringify(role)}${options.name === undefined ? "" : ` named ${describeMatcher(options.name)}`}`,
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
/** The form control a label belongs to: the element itself when it is one, else its first descendant that is. */
|
|
71
|
+
function labelled(element: TestElement): TestElement | undefined {
|
|
72
|
+
const isControl = (candidate: TestElement) => {
|
|
73
|
+
const role = candidate.role;
|
|
74
|
+
return role !== undefined && FORM_ROLES.has(role);
|
|
75
|
+
};
|
|
76
|
+
return isControl(element) ? element : element.descendants().find(isControl);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const byLabel: QueryKind<Matcher, MatcherOptions> = {
|
|
80
|
+
find: (elements, matcher, options) => {
|
|
81
|
+
const found = new Set<TestElement>();
|
|
82
|
+
for (const element of elements) {
|
|
83
|
+
const node = element.node;
|
|
84
|
+
const label = node.control?.label;
|
|
85
|
+
const role = element.role;
|
|
86
|
+
// `<label htmlFor>`: the compiled tree links the input to the label's node.
|
|
87
|
+
if (node.labelledBy?.length && matches(element.name, element, matcher, options)) found.add(element);
|
|
88
|
+
if (!label || !matches(label, element, matcher, options)) continue;
|
|
89
|
+
if (role === "field") {
|
|
90
|
+
const control = labelled(element);
|
|
91
|
+
if (control) found.add(control);
|
|
92
|
+
} else if (role === "label") {
|
|
93
|
+
// A `Label` inside a `Field` names the field's control.
|
|
94
|
+
const field = element.parent?.node.control?.role === "field" ? element.parent : undefined;
|
|
95
|
+
const control = field && labelled(field);
|
|
96
|
+
if (control) found.add(control);
|
|
97
|
+
} else if (!role || !LABEL_ONLY.has(role)) {
|
|
98
|
+
found.add(element);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return elements.filter((element) => found.has(element));
|
|
102
|
+
},
|
|
103
|
+
describe: (matcher) => `label ${describeMatcher(matcher)}`,
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const byPlaceholder: QueryKind<Matcher, MatcherOptions> = {
|
|
107
|
+
find: (elements, matcher, options) => elements.filter((element) => element.placeholder !== undefined && matches(element.placeholder, element, matcher, options)),
|
|
108
|
+
describe: (matcher) => `placeholder ${describeMatcher(matcher)}`,
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
const byDisplayValue: QueryKind<Matcher, MatcherOptions> = {
|
|
112
|
+
find: (elements, matcher, options) => elements.filter((element) => element.value !== undefined && matches(element.value, element, matcher, options)),
|
|
113
|
+
describe: (matcher) => `display value ${describeMatcher(matcher)}`,
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/** Tarve has no `data-testid`: the test id is the node id, i.e. the component's `id` prop. */
|
|
117
|
+
const byTestId: QueryKind<Matcher, MatcherOptions> = {
|
|
118
|
+
find: (elements, matcher, options) => elements.filter((element) => matches(element.id, element, matcher, { exact: true, normalizer: (text) => text, ...options })),
|
|
119
|
+
describe: (matcher) => `test id (node id) ${describeMatcher(matcher)}`,
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
type Get<M, O> = (matcher: M, options?: O) => TestElement;
|
|
123
|
+
type GetAll<M, O> = (matcher: M, options?: O) => TestElement[];
|
|
124
|
+
type Query<M, O> = (matcher: M, options?: O) => TestElement | null;
|
|
125
|
+
type Find<M, O> = (matcher: M, options?: O, waitForOptions?: WaitForOptions) => Promise<TestElement>;
|
|
126
|
+
type FindAll<M, O> = (matcher: M, options?: O, waitForOptions?: WaitForOptions) => Promise<TestElement[]>;
|
|
127
|
+
|
|
128
|
+
/** Testing Library queries over the compiled scene tree. `get*` throw, `query*` return null, `find*` wait. */
|
|
129
|
+
export interface Queries {
|
|
130
|
+
getByText: Get<Matcher, MatcherOptions>; getAllByText: GetAll<Matcher, MatcherOptions>; queryByText: Query<Matcher, MatcherOptions>;
|
|
131
|
+
queryAllByText: GetAll<Matcher, MatcherOptions>; findByText: Find<Matcher, MatcherOptions>; findAllByText: FindAll<Matcher, MatcherOptions>;
|
|
132
|
+
getByRole: Get<Role, RoleOptions>; getAllByRole: GetAll<Role, RoleOptions>; queryByRole: Query<Role, RoleOptions>;
|
|
133
|
+
queryAllByRole: GetAll<Role, RoleOptions>; findByRole: Find<Role, RoleOptions>; findAllByRole: FindAll<Role, RoleOptions>;
|
|
134
|
+
getByLabel: Get<Matcher, MatcherOptions>; getAllByLabel: GetAll<Matcher, MatcherOptions>; queryByLabel: Query<Matcher, MatcherOptions>;
|
|
135
|
+
queryAllByLabel: GetAll<Matcher, MatcherOptions>; findByLabel: Find<Matcher, MatcherOptions>; findAllByLabel: FindAll<Matcher, MatcherOptions>;
|
|
136
|
+
getByPlaceholder: Get<Matcher, MatcherOptions>; getAllByPlaceholder: GetAll<Matcher, MatcherOptions>; queryByPlaceholder: Query<Matcher, MatcherOptions>;
|
|
137
|
+
queryAllByPlaceholder: GetAll<Matcher, MatcherOptions>; findByPlaceholder: Find<Matcher, MatcherOptions>; findAllByPlaceholder: FindAll<Matcher, MatcherOptions>;
|
|
138
|
+
getByDisplayValue: Get<Matcher, MatcherOptions>; getAllByDisplayValue: GetAll<Matcher, MatcherOptions>; queryByDisplayValue: Query<Matcher, MatcherOptions>;
|
|
139
|
+
queryAllByDisplayValue: GetAll<Matcher, MatcherOptions>; findByDisplayValue: Find<Matcher, MatcherOptions>; findAllByDisplayValue: FindAll<Matcher, MatcherOptions>;
|
|
140
|
+
getByTestId: Get<Matcher, MatcherOptions>; getAllByTestId: GetAll<Matcher, MatcherOptions>; queryByTestId: Query<Matcher, MatcherOptions>;
|
|
141
|
+
queryAllByTestId: GetAll<Matcher, MatcherOptions>; findByTestId: Find<Matcher, MatcherOptions>; findAllByTestId: FindAll<Matcher, MatcherOptions>;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export interface QueryContext {
|
|
145
|
+
/** The elements in scope, in document order (read again on every query). */
|
|
146
|
+
elements(): readonly TestElement[];
|
|
147
|
+
/** Printed under a failed query. */
|
|
148
|
+
debug(): string;
|
|
149
|
+
waitFor<T>(callback: () => T | Promise<T>, options?: WaitForOptions): Promise<T>;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function bindKind<M, O>(context: QueryContext, suffix: string, kind: QueryKind<M, O>): Record<string, unknown> {
|
|
153
|
+
const fail = (message: string) => new Error(`${message}\n\n${context.debug()}`);
|
|
154
|
+
const queryAll: GetAll<M, O> = (matcher, options) => kind.find(context.elements(), matcher, options);
|
|
155
|
+
const getAll: GetAll<M, O> = (matcher, options) => {
|
|
156
|
+
const found = queryAll(matcher, options);
|
|
157
|
+
if (found.length === 0) throw fail(`Unable to find an element by ${kind.describe(matcher, options)}`);
|
|
158
|
+
return found;
|
|
159
|
+
};
|
|
160
|
+
const query: Query<M, O> = (matcher, options) => {
|
|
161
|
+
const found = queryAll(matcher, options);
|
|
162
|
+
if (found.length > 1) throw fail(`Found ${found.length} elements by ${kind.describe(matcher, options)}: ${found.join(", ")}. Use getAllBy${suffix} or a narrower query.`);
|
|
163
|
+
return found[0] ?? null;
|
|
164
|
+
};
|
|
165
|
+
const get: Get<M, O> = (matcher, options) => {
|
|
166
|
+
const found = query(matcher, options);
|
|
167
|
+
if (!found) throw fail(`Unable to find an element by ${kind.describe(matcher, options)}`);
|
|
168
|
+
return found;
|
|
169
|
+
};
|
|
170
|
+
return {
|
|
171
|
+
[`getBy${suffix}`]: get,
|
|
172
|
+
[`getAllBy${suffix}`]: getAll,
|
|
173
|
+
[`queryBy${suffix}`]: query,
|
|
174
|
+
[`queryAllBy${suffix}`]: queryAll,
|
|
175
|
+
[`findBy${suffix}`]: ((matcher, options, waitForOptions) => context.waitFor(() => get(matcher, options), waitForOptions)) satisfies Find<M, O>,
|
|
176
|
+
[`findAllBy${suffix}`]: ((matcher, options, waitForOptions) => context.waitFor(() => getAll(matcher, options), waitForOptions)) satisfies FindAll<M, O>,
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export function bindQueries(context: QueryContext): Queries {
|
|
181
|
+
return {
|
|
182
|
+
...bindKind(context, "Text", byText),
|
|
183
|
+
...bindKind(context, "Role", byRole),
|
|
184
|
+
...bindKind(context, "Label", byLabel),
|
|
185
|
+
...bindKind(context, "Placeholder", byPlaceholder),
|
|
186
|
+
...bindKind(context, "DisplayValue", byDisplayValue),
|
|
187
|
+
...bindKind(context, "TestId", byTestId),
|
|
188
|
+
} as unknown as Queries;
|
|
189
|
+
}
|