@unframework.dev/testing 0.0.0-stage → 0.2.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.
Files changed (133) hide show
  1. package/README.md +536 -2
  2. package/dist/browser/axe.js +34 -0
  3. package/dist/browser/behaviour.js +59 -0
  4. package/dist/browser/capabilities.js +58 -0
  5. package/dist/browser/clock.d.ts +17 -0
  6. package/dist/browser/clock.js +69 -0
  7. package/dist/browser/console.d.ts +27 -0
  8. package/dist/browser/console.js +142 -0
  9. package/dist/browser/determinism.js +108 -0
  10. package/dist/browser/element-timeout.js +28 -0
  11. package/dist/browser/events.js +68 -0
  12. package/dist/browser/geometry.js +135 -0
  13. package/dist/browser/keys.js +62 -0
  14. package/dist/browser/matchers.d.ts +39 -0
  15. package/dist/browser/matchers.js +78 -0
  16. package/dist/browser/navigation.js +38 -0
  17. package/dist/browser/parity.d.ts +10 -0
  18. package/dist/browser/parity.js +93 -0
  19. package/dist/browser/spec.d.ts +25 -0
  20. package/dist/browser/spec.js +38 -0
  21. package/dist/browser/target.d.ts +16 -0
  22. package/dist/browser/target.js +27 -0
  23. package/dist/browser/text-runs.js +68 -0
  24. package/dist/browser/thrown.js +71 -0
  25. package/dist/browser/trace.d.ts +21 -0
  26. package/dist/browser/trace.js +73 -0
  27. package/dist/browser/user.d.ts +45 -0
  28. package/dist/browser/user.js +184 -0
  29. package/dist/browser/view.d.ts +114 -0
  30. package/dist/browser/view.js +282 -0
  31. package/dist/browser/visual.d.ts +20 -0
  32. package/dist/browser/visual.js +36 -0
  33. package/dist/cli.d.ts +23 -0
  34. package/dist/cli.js +90 -0
  35. package/dist/commands.d.ts +107 -0
  36. package/dist/config/broadcast.js +29 -0
  37. package/dist/config/cases.d.ts +28 -0
  38. package/dist/config/cases.js +94 -0
  39. package/dist/config/index.d.ts +82 -0
  40. package/dist/config/index.js +295 -0
  41. package/dist/config/project-vite.d.ts +40 -0
  42. package/dist/config/project-vite.js +152 -0
  43. package/dist/diff.d.ts +14 -0
  44. package/dist/diff.js +92 -0
  45. package/dist/dom/serialize.js +236 -0
  46. package/dist/errors.d.ts +13 -0
  47. package/dist/errors.js +38 -0
  48. package/dist/harness.d.ts +189 -0
  49. package/dist/harness.js +53 -0
  50. package/dist/index.d.ts +16 -0
  51. package/dist/index.js +12 -0
  52. package/dist/internal.d.ts +8 -0
  53. package/dist/internal.js +6 -0
  54. package/dist/layers.d.ts +183 -0
  55. package/dist/layers.js +241 -0
  56. package/dist/node/browser.d.ts +33 -0
  57. package/dist/node/browser.js +64 -0
  58. package/dist/node/commands.d.ts +137 -0
  59. package/dist/node/commands.js +139 -0
  60. package/dist/node/context.d.ts +28 -0
  61. package/dist/node/context.js +55 -0
  62. package/dist/node/events.d.ts +25 -0
  63. package/dist/node/events.js +50 -0
  64. package/dist/node/finished.d.ts +12 -0
  65. package/dist/node/finished.js +28 -0
  66. package/dist/node/index.d.ts +21 -0
  67. package/dist/node/index.js +20 -0
  68. package/dist/node/matrix.d.ts +219 -0
  69. package/dist/node/matrix.js +309 -0
  70. package/dist/node/mode.d.ts +103 -0
  71. package/dist/node/mode.js +204 -0
  72. package/dist/node/names.d.ts +4 -0
  73. package/dist/node/names.js +5 -0
  74. package/dist/node/policy.d.ts +44 -0
  75. package/dist/node/policy.js +140 -0
  76. package/dist/node/reporter.d.ts +101 -0
  77. package/dist/node/reporter.js +251 -0
  78. package/dist/node/summary.d.ts +99 -0
  79. package/dist/node/summary.js +352 -0
  80. package/dist/node/thrown.js +78 -0
  81. package/dist/node/viewport.d.ts +7 -0
  82. package/dist/node/viewport.js +8 -0
  83. package/dist/node/visual.d.ts +85 -0
  84. package/dist/node/visual.js +373 -0
  85. package/dist/node_modules/.pnpm/playwright-core@1.63.0/node_modules/playwright-core/types/protocol.d.ts +23930 -0
  86. package/dist/node_modules/.pnpm/playwright-core@1.63.0/node_modules/playwright-core/types/structs.d.ts +22 -0
  87. package/dist/node_modules/.pnpm/playwright-core@1.63.0/node_modules/playwright-core/types/types.d.ts +22221 -0
  88. package/dist/normalize/display.js +309 -0
  89. package/dist/normalize/index.d.ts +34 -0
  90. package/dist/normalize/index.js +38 -0
  91. package/dist/normalize/pipeline.d.ts +19 -0
  92. package/dist/normalize/pipeline.js +45 -0
  93. package/dist/normalize/print.js +103 -0
  94. package/dist/normalize/rules/angular-hosts.js +53 -0
  95. package/dist/normalize/rules/aria-hosts.js +48 -0
  96. package/dist/normalize/rules/comments.js +16 -0
  97. package/dist/normalize/rules/control-values.js +65 -0
  98. package/dist/normalize/rules/engine-aliases.js +34 -0
  99. package/dist/normalize/rules/framework-attributes.js +85 -0
  100. package/dist/normalize/rules/generated-ids.js +64 -0
  101. package/dist/normalize/rules/ordering.js +39 -0
  102. package/dist/normalize/rules/qwik-styles.js +21 -0
  103. package/dist/normalize/rules/qwik-templates.js +20 -0
  104. package/dist/normalize/rules/values.js +125 -0
  105. package/dist/normalize/rules/whitespace.js +381 -0
  106. package/dist/normalize/style.js +121 -0
  107. package/dist/normalize/targets.d.ts +8 -0
  108. package/dist/normalize/targets.js +17 -0
  109. package/dist/normalize/tree.d.ts +1 -0
  110. package/dist/normalize/tree.js +151 -0
  111. package/dist/setup.d.ts +1 -0
  112. package/dist/setup.js +149 -0
  113. package/dist/ssr/index.d.ts +10 -0
  114. package/dist/ssr/index.js +103 -0
  115. package/dist/ssr/spec.d.ts +1 -0
  116. package/dist/ssr/spec.js +7 -0
  117. package/dist/targets/angular.d.ts +1 -0
  118. package/dist/targets/angular.js +5 -0
  119. package/dist/targets/astro.d.ts +1 -0
  120. package/dist/targets/astro.js +5 -0
  121. package/dist/targets/qwik.d.ts +1 -0
  122. package/dist/targets/qwik.js +5 -0
  123. package/dist/targets/react.d.ts +1 -0
  124. package/dist/targets/react.js +5 -0
  125. package/dist/targets/solid.d.ts +1 -0
  126. package/dist/targets/solid.js +5 -0
  127. package/dist/targets/svelte.d.ts +1 -0
  128. package/dist/targets/svelte.js +5 -0
  129. package/dist/targets/vue.d.ts +1 -0
  130. package/dist/targets/vue.js +5 -0
  131. package/dist/visual-types.d.ts +92 -0
  132. package/dist/visual-types.js +24 -0
  133. package/package.json +146 -3
@@ -0,0 +1,71 @@
1
+ import { caseOfFile } from "../harness.js";
2
+ import { currentTarget } from "./target.js";
3
+ import { consoleMark, excuseConsoleSince, watchConsoleErrors } from "./console.js";
4
+ import { recordLayer } from "../layers.js";
5
+ import { TestRunner, expect, inject } from "vitest";
6
+ import { commands } from "vitest/browser";
7
+ //#region src/browser/thrown.ts
8
+ /** Why the messages of the throwing step are excused from L13: the step throws on purpose. */
9
+ const EXCUSE = "the step throws on purpose, and each framework reports that in its own words";
10
+ /** The rounds of waiting for an error a framework rethrows in a task of its own. */
11
+ const SETTLE_ROUNDS = 3;
12
+ /**
13
+ * Runs `step`, which must make the component throw, and records L14 from the first `Error` it
14
+ * raised. Vitest treats a window `error` as a failure of the run only while no page listener is
15
+ * registered, so these listeners also keep the deliberate throw from failing it.
16
+ */
17
+ async function expectThrown(host, step) {
18
+ const test = TestRunner.getCurrentTest();
19
+ if (!test) throw new Error("expectThrown must be called inside a test.");
20
+ const harness = inject("ufHarness");
21
+ const subject = {
22
+ case: caseOfFile(test.file.filepath, harness),
23
+ target: currentTarget(),
24
+ quarantine: harness.quarantine
25
+ };
26
+ let thrown;
27
+ let logged;
28
+ const take = (value) => {
29
+ if (value instanceof Error) thrown ??= value;
30
+ };
31
+ const onError = (event) => take(event.error);
32
+ const onRejection = (event) => take(event.reason);
33
+ const unwatch = watchConsoleErrors((value) => {
34
+ if (value instanceof Error) logged ??= value;
35
+ });
36
+ window.addEventListener("error", onError);
37
+ window.addEventListener("unhandledrejection", onRejection);
38
+ const console = consoleMark();
39
+ const steps = host.stepMark();
40
+ try {
41
+ await step().catch(take);
42
+ for (let round = 0; round < SETTLE_ROUNDS; round += 1) {
43
+ await host.settle().catch(take);
44
+ await new Promise((resolve) => setTimeout(resolve, 0));
45
+ }
46
+ } finally {
47
+ window.removeEventListener("error", onError);
48
+ window.removeEventListener("unhandledrejection", onRejection);
49
+ unwatch();
50
+ }
51
+ excuseConsoleSince(console, EXCUSE);
52
+ host.forgetSteps(steps);
53
+ const first = thrown ?? logged;
54
+ const failure = await problem(subject.case, first);
55
+ recordLayer(test, subject, "L14", failure ? {
56
+ status: "fail",
57
+ message: failure
58
+ } : { status: "pass" });
59
+ expect(first).toBeInstanceOf(Error);
60
+ }
61
+ /** What is wrong with the captured error's mapped stack, or nothing. */
62
+ async function problem(caseId, error) {
63
+ if (!error) return "The step threw no Error.";
64
+ const { message } = await commands.ufMapStack({
65
+ case: caseId,
66
+ stack: error.stack ?? ""
67
+ });
68
+ return message;
69
+ }
70
+ //#endregion
71
+ export { expectThrown };
@@ -0,0 +1,21 @@
1
+ //#region src/browser/trace.d.ts
2
+ /** One scripted step, after it settled. */
3
+ export interface TraceStep {
4
+ /**
5
+ * What happened, the same on every target: the action, the locator under the view's root,
6
+ * and the action's arguments as JSON (`click getByRole('button', { name: '+3' })`,
7
+ * `fill getByLabelText('Name') "Ada"`, `rerender {"label":"New"}`).
8
+ */
9
+ action: string;
10
+ /** The normalised DOM, one line each, the focused element marked `uf:focused`. */
11
+ dom: string[];
12
+ /** Playwright's ARIA snapshot of the root, one line each. */
13
+ aria: string[];
14
+ /**
15
+ * The events emitted since the step before (or since the mount), grouped by name: names
16
+ * sorted, each name's argument lists in the order they came (the order of different effects
17
+ * one run triggers is not part of the contract, ADR-0050).
18
+ */
19
+ events: Record<string, unknown[][]>;
20
+ }
21
+ //#endregion
@@ -0,0 +1,73 @@
1
+ import { renameGeneratedIds } from "../normalize/rules/generated-ids.js";
2
+ import { groupEvents, renumberIds } from "./events.js";
3
+ /** The steps of one view not yet compared, and the events they have seen. */
4
+ var Trace = class {
5
+ #source;
6
+ #steps = [];
7
+ /** How many of the view's events earlier steps took. */
8
+ #cursor = 0;
9
+ constructor(source) {
10
+ this.#source = source;
11
+ open.add(this);
12
+ }
13
+ /** Records a step, after the action settled. */
14
+ async record(action) {
15
+ const { html, ids } = this.#source.dom();
16
+ const names = new Map(ids);
17
+ const aria = renameGeneratedIds(await this.#source.aria(), names);
18
+ const events = this.#source.events.slice(this.#cursor);
19
+ this.#cursor += events.length;
20
+ this.#steps.push({
21
+ action,
22
+ dom: lines(html),
23
+ aria: lines(aria),
24
+ events: groupEvents(events.map((event) => ({
25
+ ...event,
26
+ args: renumberIds(event.args, names)
27
+ })))
28
+ });
29
+ }
30
+ /** The steps since the previous call, which `expectParity` compares; the trace forgets them. */
31
+ take() {
32
+ return this.#steps.splice(0);
33
+ }
34
+ /** How many steps are waiting to be compared. */
35
+ get length() {
36
+ return this.#steps.length;
37
+ }
38
+ /** Forgets the steps since the trace held `length` of them: they are no scenario to compare. */
39
+ forget(length) {
40
+ this.#steps.length = length;
41
+ }
42
+ /** The steps not taken yet, as a message, or nothing. */
43
+ leftover() {
44
+ if (!this.#steps.length) return void 0;
45
+ const actions = this.#steps.map((step) => step.action).join("; ");
46
+ return `${this.#steps.length} step(s) of ${this.#source.root} were never compared (${actions}): every view.user action and rerender is followed by an expectParity, which compares its trace.`;
47
+ }
48
+ };
49
+ /** Every trace of the current test, which the setup file judges when it ends. */
50
+ const open = /* @__PURE__ */ new Set();
51
+ /**
52
+ * The steps of the current test's views that no `expectParity` compared, as L9's failures, and
53
+ * forgets every trace: the setup file calls it when a test ends.
54
+ */
55
+ function closeTraces() {
56
+ const messages = [...open].flatMap((trace) => trace.leftover() ?? []);
57
+ open.clear();
58
+ return messages;
59
+ }
60
+ /** A trace file's contents: pretty JSON, so a diff names the line that changed. */
61
+ function traceFile(steps) {
62
+ return `${JSON.stringify({
63
+ version: 1,
64
+ steps
65
+ }, null, 2)}\n`;
66
+ }
67
+ /** Text as lines, without the final line break. */
68
+ function lines(text) {
69
+ const trimmed = text.replace(/\n+$/, "");
70
+ return trimmed ? trimmed.split("\n") : [];
71
+ }
72
+ //#endregion
73
+ export { Trace, closeTraces, traceFile };
@@ -0,0 +1,45 @@
1
+ import "../commands.js";
2
+ import { Locator, UserEventWheelOptions } from "vitest/browser";
3
+ //#region src/browser/user.d.ts
4
+ /** Where a click presses: a point from the element's top left corner, its centre by default. */
5
+ export interface ClickOptions {
6
+ position?: {
7
+ x: number;
8
+ y: number;
9
+ };
10
+ }
11
+ /** A person's input to one mounted view. Every target accepts a locator under the view's root. */
12
+ export interface ViewUser {
13
+ /** Moves the mouse onto the element, then presses and releases its main button. */
14
+ click(target: Locator, options?: ClickOptions): Promise<void>;
15
+ /** Moves the mouse onto the element, then presses and releases its main button twice. */
16
+ dblClick(target: Locator): Promise<void>;
17
+ /** Moves the mouse onto the element, then presses and releases its main button three times. */
18
+ tripleClick(target: Locator): Promise<void>;
19
+ /** Moves the mouse over the element. */
20
+ hover(target: Locator): Promise<void>;
21
+ /** Moves the mouse off the element, onto the page's body. */
22
+ unhover(target: Locator): Promise<void>;
23
+ /** Focuses a field, then replaces its text with `text`, as pasting it would. */
24
+ fill(target: Locator, text: string): Promise<void>;
25
+ /**
26
+ * Focuses the element, then presses and releases each key of `text` in turn (`{Enter}` names a
27
+ * key, `{Shift>}` holds it, `{/Shift}` releases it), then releases every key still held.
28
+ */
29
+ type(target: Locator, text: string): Promise<void>;
30
+ /** Focuses a field, then removes all its text. */
31
+ clear(target: Locator): Promise<void>;
32
+ /** Presses and releases each key of `text` where the focus is (`{Escape}`, `abc`), as `type`. */
33
+ keyboard(text: string): Promise<void>;
34
+ /** Moves the focus to the next (or, with `shift`, the previous) focusable element. */
35
+ tab(options?: {
36
+ shift?: boolean;
37
+ }): Promise<void>;
38
+ /** Moves the focus to the element, as a script's `element.focus()` would. */
39
+ focus(target: Locator): Promise<void>;
40
+ /** Selects the options of a `<select>` with these values or labels. */
41
+ selectOptions(target: Locator, values: string | readonly string[]): Promise<void>;
42
+ /** Moves the mouse onto the element, then turns the wheel, a step at a time. */
43
+ wheel(target: Locator, options: UserEventWheelOptions): Promise<void>;
44
+ }
45
+ //#endregion
@@ -0,0 +1,184 @@
1
+ import { assertInteractive } from "./capabilities.js";
2
+ import { isCharacter, parseKeys } from "./keys.js";
3
+ import { commands, userEvent } from "vitest/browser";
4
+ //#region src/browser/user.ts
5
+ /**
6
+ * The keys held down, across actions, as the page's keyboard holds them: `{Shift>}` adds one,
7
+ * `{/Shift}` removes it. The page is one per test file, so this is too.
8
+ */
9
+ const held = /* @__PURE__ */ new Set();
10
+ /** The user of a view. */
11
+ function createUser(host) {
12
+ const act = async (kind, target, args, inputs) => {
13
+ assertInteractive(`view.user.${kind}`);
14
+ const parts = [
15
+ kind,
16
+ ...target === void 0 ? [] : [underRoot(host.testId, target, kind)],
17
+ ...args.filter((arg) => arg !== void 0).map((arg) => JSON.stringify(arg))
18
+ ];
19
+ return host.perform(parts.join(" "), inputs());
20
+ };
21
+ return {
22
+ click: (target, options) => act("click", target, [nonEmpty(options)], () => clicks(target, 1, options?.position)),
23
+ dblClick: (target) => act("dblClick", target, [], () => clicks(target, 2)),
24
+ tripleClick: (target) => act("tripleClick", target, [], () => clicks(target, 3)),
25
+ hover: (target) => act("hover", target, [], () => [send({
26
+ kind: "move",
27
+ locator: target.serialize(),
28
+ check: "hover"
29
+ })]),
30
+ unhover: (target) => act("unhover", target, [], () => [() => userEvent.unhover(target)]),
31
+ fill: (target, text) => act("fill", target, [text], () => [focus(target), () => userEvent.fill(target, text)]),
32
+ type: (target, text) => act("type", target, [text], () => {
33
+ const keys = parseKeys(text, "view.user.type", held);
34
+ return (function* () {
35
+ yield focus(target);
36
+ yield* press(keys);
37
+ for (const key of [...held].toReversed()) yield release(key);
38
+ })();
39
+ }),
40
+ clear: (target) => act("clear", target, [], () => [focus(target), () => userEvent.clear(target)]),
41
+ keyboard: (text) => act("keyboard", void 0, [text], () => {
42
+ const keys = parseKeys(text, "view.user.keyboard", held);
43
+ return (function* () {
44
+ const active = document.activeElement;
45
+ if (!active || active === document.body) window.focus();
46
+ yield* press(keys);
47
+ })();
48
+ }),
49
+ tab: (options = {}) => {
50
+ const shift = options.shift === true;
51
+ return act("tab", void 0, [shift ? { shift: true } : void 0], () => {
52
+ const keys = parseKeys(shift ? "{Shift>}{Tab}{/Shift}" : "{Tab}", "view.user.tab", held);
53
+ return (function* () {
54
+ window.focus();
55
+ yield* press(keys);
56
+ })();
57
+ });
58
+ },
59
+ focus: (target) => act("focus", target, [], () => [focus(target)]),
60
+ selectOptions: (target, values) => {
61
+ const list = typeof values === "string" ? [values] : [...values];
62
+ return act("selectOptions", target, [list], () => [() => userEvent.selectOptions(target, list)]);
63
+ },
64
+ wheel: (target, options) => act("wheel", target, [options], () => {
65
+ const { deltaX, deltaY, times } = wheelSteps(options);
66
+ return (function* () {
67
+ yield send({
68
+ kind: "move",
69
+ locator: target.serialize(),
70
+ check: "hover"
71
+ });
72
+ for (let step = 0; step < times; step += 1) yield send({
73
+ kind: "wheel",
74
+ deltaX,
75
+ deltaY
76
+ });
77
+ })();
78
+ })
79
+ };
80
+ }
81
+ /** An input `ufInput` dispatches. */
82
+ function send(request) {
83
+ return async () => {
84
+ await commands.ufInput(request);
85
+ };
86
+ }
87
+ /** The focus moved to the element, as Playwright's `locator.focus()` does. */
88
+ function focus(target) {
89
+ return async () => {
90
+ await commands.ufFocus(target.serialize());
91
+ };
92
+ }
93
+ /** The mouse moved onto the element, then its main button pressed and released `count` times. */
94
+ function clicks(target, count, position) {
95
+ const inputs = [send({
96
+ kind: "move",
97
+ locator: target.serialize(),
98
+ ...position ? { position } : {},
99
+ check: "click"
100
+ })];
101
+ for (let clickCount = 1; clickCount <= count; clickCount += 1) inputs.push(send({
102
+ kind: "press",
103
+ clickCount
104
+ }), send({
105
+ kind: "release",
106
+ clickCount
107
+ }));
108
+ return inputs;
109
+ }
110
+ /**
111
+ * Each key's press and its release, as inputs of their own. A character the keyboard layout
112
+ * lacks is inserted as text, and has no release. Read lazily: whether a key is held is known
113
+ * once its press has run.
114
+ */
115
+ function* press(keys) {
116
+ for (const { key, text, press: down, release: up } of keys) {
117
+ if (down) yield async () => {
118
+ const { inserted } = await commands.ufInput({
119
+ kind: "keydown",
120
+ key,
121
+ text
122
+ });
123
+ if (!inserted) held.add(key);
124
+ };
125
+ if (up && held.has(key)) yield release(key);
126
+ }
127
+ }
128
+ /** A held key's release. */
129
+ function release(key) {
130
+ return async () => {
131
+ await commands.ufInput({
132
+ kind: "keyup",
133
+ key,
134
+ text: isCharacter(key)
135
+ });
136
+ held.delete(key);
137
+ };
138
+ }
139
+ /**
140
+ * Releases every key a test left held, after its views are unmounted, so the next test starts
141
+ * with none. Nothing settles: no view is left to settle.
142
+ */
143
+ async function releaseKeys() {
144
+ for (const key of [...held].toReversed()) await release(key)();
145
+ }
146
+ /** The wheel's steps, as Vitest's `wheel` reads its options: a direction is 100 pixels. */
147
+ function wheelSteps(options) {
148
+ const times = options.times ?? 1;
149
+ if (!Number.isSafeInteger(times) || times < 1) throw new TypeError(`view.user.wheel: the wheel turns a positive whole number of times, not ${String(times)}.`);
150
+ if (options.delta) return {
151
+ deltaX: options.delta.x ?? 0,
152
+ deltaY: options.delta.y ?? 0,
153
+ times
154
+ };
155
+ const [deltaX, deltaY] = {
156
+ up: [0, -100],
157
+ down: [0, 100],
158
+ left: [-100, 0],
159
+ right: [100, 0]
160
+ }[options.direction];
161
+ return {
162
+ deltaX,
163
+ deltaY,
164
+ times
165
+ };
166
+ }
167
+ /**
168
+ * The part of a locator under the view's root (`getByRole('button', { name: '+3' })`), which a
169
+ * step's action names on every target. Refuses anything else: an element (its selector would be
170
+ * built from the DOM, which differs by target), the root itself, a locator of the page or of
171
+ * another view, whose root's number depends on the mount order.
172
+ */
173
+ function underRoot(testId, target, kind) {
174
+ const serialized = typeof target === "object" && target !== null && "serialize" in target ? target.serialize().locator : void 0;
175
+ const prefix = `getByTestId('${testId}').`;
176
+ if (serialized === void 0 || !serialized.startsWith(prefix)) throw new TypeError(`view.user.${kind}: act on a locator of this view, such as view.getByRole("button", { name: "Save" }), not ${serialized === void 0 ? "an element" : serialized}: a step names its target the same way on every target.`);
177
+ return serialized.slice(prefix.length);
178
+ }
179
+ /** An options object, or nothing when it has no options set. */
180
+ function nonEmpty(options) {
181
+ return options && Object.keys(options).length ? options : void 0;
182
+ }
183
+ //#endregion
184
+ export { createUser, releaseKeys };
@@ -0,0 +1,114 @@
1
+ import "../commands.js";
2
+ import { ParityOptions } from "./parity.js";
3
+ import { ViewClock } from "./clock.js";
4
+ import { ViewUser } from "./user.js";
5
+ import { Locator } from "vitest/browser";
6
+ import { MountOptions } from "@unframework.dev/codegen";
7
+ //#region src/browser/view.d.ts
8
+ /** Props as an adapter takes them. */
9
+ export type Props = Readonly<Record<string, unknown>>;
10
+ /** A mounted component. Queries are scoped to its container. */
11
+ export interface View<P = Props> {
12
+ readonly target: string;
13
+ /**
14
+ * The mount root: a `<div data-uf-root>` directly in the page's `<body>`. No landmark wraps
15
+ * it: the page a component is rendered into owns the landmarks, and a harness `<main>` would
16
+ * make a component's own `<main>` a nested, duplicate one for axe (L11).
17
+ */
18
+ readonly container: HTMLElement;
19
+ /** The container's locator: `page.getByTestId("uf-root-N")`, which stays valid as the DOM changes. */
20
+ readonly locator: Locator;
21
+ readonly getByRole: Locator["getByRole"];
22
+ readonly getByText: Locator["getByText"];
23
+ readonly getByLabelText: Locator["getByLabelText"];
24
+ readonly getByPlaceholder: Locator["getByPlaceholder"];
25
+ readonly getByAltText: Locator["getByAltText"];
26
+ readonly getByTitle: Locator["getByTitle"];
27
+ readonly getByTestId: Locator["getByTestId"];
28
+ /**
29
+ * A person's input to this view: each action runs through the target's adapter, settles until
30
+ * the page is quiet, and records a step of the view's trace, which the next `expectParity`
31
+ * compares (L9). It throws on a target that runs no client code: such a test declares
32
+ * `requires: ["interactivity"]`.
33
+ */
34
+ readonly user: ViewUser;
35
+ /**
36
+ * The page's fake clock, for a view mounted with `{ clock: true }`: `tick(ms)` runs the
37
+ * component's intervals due in the next `ms` milliseconds, one at a time and settled after
38
+ * each, and records a step of the trace, `tick <ms>ms`, holding what they emitted, as an
39
+ * action does. Throws for a view mounted without one.
40
+ */
41
+ readonly clock: ViewClock;
42
+ /** The container's content as normalised HTML, the form L7 compares. */
43
+ html(): string;
44
+ /** Waits for the framework to flush, the fonts and two frames. */
45
+ settle(): Promise<void>;
46
+ /**
47
+ * Renders the component again with new props, as a parent that re-renders it would, and
48
+ * waits until it has settled, as `mount` does. The props are replaced whole: a prop `props`
49
+ * lacks takes its default again (plan §7.2, L8). It records a step of the trace, as an action
50
+ * does.
51
+ */
52
+ rerender(props: P): Promise<void>;
53
+ /**
54
+ * The arguments of each emit of an event the component declares (`emitted("change")` →
55
+ * `[[5]]`), in order, as plain data, with generated ids renamed as `html()` renames them.
56
+ * Throws for an event the component does not declare, and on a target that runs no client
57
+ * code.
58
+ */
59
+ emitted(name: string): unknown[][];
60
+ /** Every emit, in order, as `[name, ...args]`; as {@link View.emitted}. */
61
+ events(): unknown[][];
62
+ /**
63
+ * Verifies L7, L9, L10 and L11 for a scenario against the case's shared expectations: L9 the
64
+ * steps since the mount or the previous `expectParity`.
65
+ */
66
+ expectParity(name: string, options?: ParityOptions): Promise<void>;
67
+ /**
68
+ * Runs a `view.user` step that makes the component throw, and verifies L14: the first `Error`'s
69
+ * top frame in the case maps to the one line of the case's source that holds `throw` (ADR-0078).
70
+ * What the step logs is excused from L13, and it records no step of the trace, since what a
71
+ * framework leaves behind after a throw is no contract.
72
+ */
73
+ expectThrown(step: () => Promise<void>): Promise<void>;
74
+ unmount(): Promise<void>;
75
+ }
76
+ /** How a view runs, beside the props it mounts with. */
77
+ export interface ViewOptions {
78
+ /**
79
+ * Fakes the page's `setInterval` and `clearInterval` before the component mounts, so its
80
+ * intervals fire only when the spec advances `view.clock`, each tick inside a step (ADR-0050).
81
+ * Only one view of a test may have it; the setup gives the page its real timers back when the
82
+ * test ends.
83
+ */
84
+ clock?: boolean;
85
+ }
86
+ /** How a test mounts a component whose props have a type: with props of that type. */
87
+ export interface ComponentMountOptions<P> extends ViewOptions {
88
+ props?: P;
89
+ }
90
+ /**
91
+ * What a function component cannot be: the untyped overloads take the test stubs' plain
92
+ * objects only, so a component's props are never checked against `MountOptions` instead of
93
+ * its own type.
94
+ */
95
+ export type NotAFunction<C> = C extends ((...args: never[]) => unknown) ? never : C;
96
+ /**
97
+ * Mounts a compiled component with the project's adapter and waits until it has settled. A
98
+ * component imported from a `.uf.tsx` is typed as its authored function, so its props are
99
+ * checked against its own props type.
100
+ */
101
+ export declare function mount<P>(component: (props: P) => unknown, options?: ComponentMountOptions<NoInfer<P>>): Promise<View<P>>;
102
+ /** Mounts what is not a function component, such as a test stub. */
103
+ export declare function mount<C extends object>(component: NotAFunction<C>, options?: MountOptions & ViewOptions): Promise<View>;
104
+ /**
105
+ * Mounts a component with the props of one of the case's SSR scenarios, `case.json`'s
106
+ * `ssr[name].props`, so the browser scenario and its server twin render the same props. The
107
+ * test then checks it with `expectParity(name)` under the same name.
108
+ */
109
+ export declare function mountScenario<P>(component: (props: P) => unknown, name: string, options?: ViewOptions): Promise<View<P>>;
110
+ /** Mounts what is not a function component, such as a test stub, with a scenario's props. */
111
+ export declare function mountScenario<C extends object>(component: NotAFunction<C>, name: string, options?: ViewOptions): Promise<View>;
112
+ /** Unmounts every view the current test left mounted, newest first. */
113
+ export declare function cleanup(): Promise<void>;
114
+ //#endregion