@unframework.dev/testing 0.0.0-stage → 0.0.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 (131) hide show
  1. package/README.md +511 -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 +81 -0
  40. package/dist/config/index.js +275 -0
  41. package/dist/diff.d.ts +14 -0
  42. package/dist/diff.js +92 -0
  43. package/dist/dom/serialize.js +236 -0
  44. package/dist/errors.d.ts +13 -0
  45. package/dist/errors.js +38 -0
  46. package/dist/harness.d.ts +184 -0
  47. package/dist/harness.js +53 -0
  48. package/dist/index.d.ts +16 -0
  49. package/dist/index.js +12 -0
  50. package/dist/internal.d.ts +8 -0
  51. package/dist/internal.js +6 -0
  52. package/dist/layers.d.ts +183 -0
  53. package/dist/layers.js +241 -0
  54. package/dist/node/browser.d.ts +33 -0
  55. package/dist/node/browser.js +64 -0
  56. package/dist/node/commands.d.ts +137 -0
  57. package/dist/node/commands.js +139 -0
  58. package/dist/node/context.d.ts +28 -0
  59. package/dist/node/context.js +55 -0
  60. package/dist/node/events.d.ts +25 -0
  61. package/dist/node/events.js +50 -0
  62. package/dist/node/finished.d.ts +12 -0
  63. package/dist/node/finished.js +28 -0
  64. package/dist/node/index.d.ts +21 -0
  65. package/dist/node/index.js +20 -0
  66. package/dist/node/matrix.d.ts +219 -0
  67. package/dist/node/matrix.js +309 -0
  68. package/dist/node/mode.d.ts +101 -0
  69. package/dist/node/mode.js +201 -0
  70. package/dist/node/names.d.ts +4 -0
  71. package/dist/node/names.js +5 -0
  72. package/dist/node/policy.d.ts +44 -0
  73. package/dist/node/policy.js +140 -0
  74. package/dist/node/reporter.d.ts +101 -0
  75. package/dist/node/reporter.js +251 -0
  76. package/dist/node/summary.d.ts +99 -0
  77. package/dist/node/summary.js +352 -0
  78. package/dist/node/thrown.js +78 -0
  79. package/dist/node/viewport.d.ts +7 -0
  80. package/dist/node/viewport.js +8 -0
  81. package/dist/node/visual.d.ts +85 -0
  82. package/dist/node/visual.js +370 -0
  83. package/dist/node_modules/.pnpm/playwright-core@1.63.0/node_modules/playwright-core/types/protocol.d.ts +23930 -0
  84. package/dist/node_modules/.pnpm/playwright-core@1.63.0/node_modules/playwright-core/types/structs.d.ts +22 -0
  85. package/dist/node_modules/.pnpm/playwright-core@1.63.0/node_modules/playwright-core/types/types.d.ts +22221 -0
  86. package/dist/normalize/display.js +309 -0
  87. package/dist/normalize/index.d.ts +34 -0
  88. package/dist/normalize/index.js +38 -0
  89. package/dist/normalize/pipeline.d.ts +19 -0
  90. package/dist/normalize/pipeline.js +45 -0
  91. package/dist/normalize/print.js +103 -0
  92. package/dist/normalize/rules/angular-hosts.js +53 -0
  93. package/dist/normalize/rules/aria-hosts.js +48 -0
  94. package/dist/normalize/rules/comments.js +16 -0
  95. package/dist/normalize/rules/control-values.js +65 -0
  96. package/dist/normalize/rules/engine-aliases.js +34 -0
  97. package/dist/normalize/rules/framework-attributes.js +85 -0
  98. package/dist/normalize/rules/generated-ids.js +64 -0
  99. package/dist/normalize/rules/ordering.js +39 -0
  100. package/dist/normalize/rules/qwik-styles.js +21 -0
  101. package/dist/normalize/rules/qwik-templates.js +20 -0
  102. package/dist/normalize/rules/values.js +125 -0
  103. package/dist/normalize/rules/whitespace.js +381 -0
  104. package/dist/normalize/style.js +121 -0
  105. package/dist/normalize/targets.d.ts +8 -0
  106. package/dist/normalize/targets.js +17 -0
  107. package/dist/normalize/tree.d.ts +1 -0
  108. package/dist/normalize/tree.js +151 -0
  109. package/dist/setup.d.ts +1 -0
  110. package/dist/setup.js +149 -0
  111. package/dist/ssr/index.d.ts +10 -0
  112. package/dist/ssr/index.js +103 -0
  113. package/dist/ssr/spec.d.ts +1 -0
  114. package/dist/ssr/spec.js +7 -0
  115. package/dist/targets/angular.d.ts +1 -0
  116. package/dist/targets/angular.js +5 -0
  117. package/dist/targets/astro.d.ts +1 -0
  118. package/dist/targets/astro.js +5 -0
  119. package/dist/targets/qwik.d.ts +1 -0
  120. package/dist/targets/qwik.js +5 -0
  121. package/dist/targets/react.d.ts +1 -0
  122. package/dist/targets/react.js +5 -0
  123. package/dist/targets/solid.d.ts +1 -0
  124. package/dist/targets/solid.js +5 -0
  125. package/dist/targets/svelte.d.ts +1 -0
  126. package/dist/targets/svelte.js +5 -0
  127. package/dist/targets/vue.d.ts +1 -0
  128. package/dist/targets/vue.js +5 -0
  129. package/dist/visual-types.d.ts +92 -0
  130. package/dist/visual-types.js +24 -0
  131. package/package.json +135 -3
@@ -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
@@ -0,0 +1,282 @@
1
+ import { caseOfFile } from "../harness.js";
2
+ import { registeredAdapter } from "./target.js";
3
+ import { captureExternalConsole } from "./console.js";
4
+ import { formatError } from "../errors.js";
5
+ import { recordLayer } from "../layers.js";
6
+ import { assertInteractive } from "./capabilities.js";
7
+ import { isNormalizeTarget } from "../normalize/targets.js";
8
+ import { normalizeDomWithIds } from "../dom/serialize.js";
9
+ import { inlineHosts } from "../normalize/rules/aria-hosts.js";
10
+ import { advanceClock, checkTick, installClock } from "./clock.js";
11
+ import { ROOT_ATTRIBUTE, installDeterminism, settleFrame } from "./determinism.js";
12
+ import { copyPayload, renumberIds } from "./events.js";
13
+ import { takePreventedNavigations } from "./navigation.js";
14
+ import { Trace } from "./trace.js";
15
+ import { expectParity } from "./parity.js";
16
+ import { expectThrown } from "./thrown.js";
17
+ import { createUser } from "./user.js";
18
+ import { TestRunner, inject } from "vitest";
19
+ import { commands, page } from "vitest/browser";
20
+ //#region src/browser/view.ts
21
+ /** The rounds of settling after an action before the page counts as never quiet. */
22
+ const SETTLE_ROUNDS = 10;
23
+ const mounted = /* @__PURE__ */ new Set();
24
+ let roots = 0;
25
+ function mount(component, options = {}) {
26
+ return mountWith(component, options.props, options);
27
+ }
28
+ async function mountScenario(component, name, options = {}) {
29
+ const caseId = currentCase("mountScenario");
30
+ const scenarios = inject("ufHarness").cases[caseId]?.ssr ?? {};
31
+ if (!Object.hasOwn(scenarios, name)) {
32
+ const declared = Object.keys(scenarios);
33
+ throw new Error(`mountScenario(…, "${name}"): ${caseId}'s case.json declares no SSR scenario "${name}" (${declared.length ? `it declares ${declared.join(", ")}` : "it declares none"}). Declare it under "ssr" with its props, or mount a browser-only scenario with mount(component, { props }).`);
34
+ }
35
+ const props = scenarios[name]?.props;
36
+ return mountWith(component, props === void 0 ? void 0 : structuredClone(props), options);
37
+ }
38
+ /** The current test's case. */
39
+ function currentCase(caller) {
40
+ const test = TestRunner.getCurrentTest();
41
+ if (!test) throw new Error(`${caller} must be called inside a test.`);
42
+ return caseOfFile(test.file.filepath, inject("ufHarness"));
43
+ }
44
+ /**
45
+ * The events a component declares: from the stub target's registration, or from the project's
46
+ * compile of the case's module (the `ufComponentEvents` command), never from a guess.
47
+ */
48
+ async function declaredEvents(registration, component) {
49
+ if (registration.events) return registration.events(component);
50
+ const { events } = await commands.ufComponentEvents({ case: currentCase("mount") });
51
+ return events;
52
+ }
53
+ async function mountWith(component, props, { clock = false }) {
54
+ const registration = registeredAdapter();
55
+ const { target, mount: adapter } = registration;
56
+ const initial = checkProps("mount", props);
57
+ await installDeterminism();
58
+ const declared = await declaredEvents(registration, component);
59
+ const log = [];
60
+ const refused = [];
61
+ const on = Object.fromEntries(declared.map(({ name }) => [name, (...args) => {
62
+ try {
63
+ log.push({
64
+ name,
65
+ args: copyPayload(name, args)
66
+ });
67
+ } catch (error) {
68
+ refused.push(formatError(error));
69
+ }
70
+ }]));
71
+ if (clock) installClock();
72
+ const container = document.createElement("div");
73
+ const testId = `uf-root-${roots += 1}`;
74
+ container.setAttribute(ROOT_ATTRIBUTE, "");
75
+ container.setAttribute("data-testid", testId);
76
+ document.body.append(container);
77
+ let instance;
78
+ try {
79
+ instance = await adapter(component, container, {
80
+ ...initial ? { props: initial } : {},
81
+ on,
82
+ events: declared
83
+ });
84
+ } catch (error) {
85
+ container.remove();
86
+ throw error;
87
+ }
88
+ report(instance);
89
+ const locator = page.getByTestId(testId);
90
+ const engine = inject("ufHarness")?.browser;
91
+ const normalizeOptions = {
92
+ ...isNormalizeTarget(target) ? { target } : {},
93
+ ...engine ? { engine } : {}
94
+ };
95
+ const dom = () => normalizeDomWithIds(container, normalizeOptions);
96
+ const html = () => dom().html;
97
+ const aria = async () => {
98
+ const restore = inlineHosts(container, isNormalizeTarget(target) ? target : void 0);
99
+ try {
100
+ return await commands.ufAriaSnapshot(locator.serialize());
101
+ } finally {
102
+ restore();
103
+ }
104
+ };
105
+ /** Fails with what the page or the payloads refused since the last settle. */
106
+ const raise = () => {
107
+ const problems = [...takePreventedNavigations(), ...refused.splice(0)];
108
+ if (problems.length) throw new Error(problems.join("\n"));
109
+ };
110
+ const settle = async () => {
111
+ await settleFrame(() => instance.settle());
112
+ raise();
113
+ };
114
+ /**
115
+ * Settles until the DOM and the emitted events stop changing: two rounds in a row read the
116
+ * same. A handler's work after an `await`, an effect a write scheduled, a lazily loaded
117
+ * handler: each lands in some round, and every target's step records all of it. Once the
118
+ * view is unmounted, a round waits for the page alone: the adapter has nothing left to settle.
119
+ */
120
+ const settleUntilQuiet = async (settleOnce = settle) => {
121
+ let previous;
122
+ for (let round = 0; round < SETTLE_ROUNDS; round += 1) {
123
+ await settleOnce();
124
+ const snapshot = `${html()}\n${log.length}`;
125
+ if (snapshot === previous) return true;
126
+ previous = snapshot;
127
+ }
128
+ return false;
129
+ };
130
+ const trace = new Trace({
131
+ root: testId,
132
+ dom,
133
+ aria,
134
+ events: log
135
+ });
136
+ /** Settles after a step and records it; a page that never quiets fails L9, which it feeds. */
137
+ const step = async (action) => {
138
+ if (!await settleUntilQuiet()) failTrace(target, `did not settle after ${action}`);
139
+ await trace.record(action);
140
+ };
141
+ let unmounted = false;
142
+ /**
143
+ * Runs an action as a step of the view: each input through the adapter and settled before the
144
+ * next is taken (as the time between a person's two inputs lets a framework render), then the
145
+ * step is recorded.
146
+ */
147
+ const perform = async (action, inputs) => {
148
+ if (unmounted) throw new Error(`${action}: the view is unmounted.`);
149
+ const pending = inputs[Symbol.iterator]();
150
+ for (let next = pending.next(); !next.done;) {
151
+ const input = next.value;
152
+ await (instance.interact ? instance.interact(input) : input());
153
+ next = pending.next();
154
+ if (!next.done && !await settleUntilQuiet()) failTrace(target, `did not settle after an input of ${action}`);
155
+ }
156
+ await step(action);
157
+ };
158
+ const declaredNames = declared.map(({ name }) => name);
159
+ const emittedArgs = (what) => {
160
+ assertInteractive(what);
161
+ raise();
162
+ const { ids } = dom();
163
+ return log.map((event) => ({
164
+ ...event,
165
+ args: renumberIds(event.args, ids)
166
+ }));
167
+ };
168
+ const view = {
169
+ target,
170
+ container,
171
+ locator,
172
+ getByRole: (...args) => locator.getByRole(...args),
173
+ getByText: (...args) => locator.getByText(...args),
174
+ getByLabelText: (...args) => locator.getByLabelText(...args),
175
+ getByPlaceholder: (...args) => locator.getByPlaceholder(...args),
176
+ getByAltText: (...args) => locator.getByAltText(...args),
177
+ getByTitle: (...args) => locator.getByTitle(...args),
178
+ getByTestId: (...args) => locator.getByTestId(...args),
179
+ user: createUser({
180
+ testId,
181
+ perform
182
+ }),
183
+ clock: { async tick(ms) {
184
+ assertInteractive("view.clock.tick");
185
+ if (!clock) throw new Error("view.clock.tick: this view was mounted without a clock. Mount it with { clock: true }, which fakes setInterval before the component starts its intervals.");
186
+ checkTick(ms);
187
+ const action = `tick ${ms}ms`;
188
+ if (!unmounted) {
189
+ await advanceClock(ms, async (fire) => {
190
+ await (instance.interact ? instance.interact(fire) : fire());
191
+ if (!await settleUntilQuiet()) failTrace(target, `did not settle after an interval that ${action} ran`);
192
+ });
193
+ await step(action);
194
+ return;
195
+ }
196
+ const settlePage = async () => {
197
+ await settleFrame();
198
+ raise();
199
+ };
200
+ await advanceClock(ms, async (fire) => {
201
+ await fire();
202
+ if (!await settleUntilQuiet(settlePage)) throw new Error(`view.clock.tick: the page did not settle after an interval of ${action} once the view was unmounted: its emitted events still changed after ${SETTLE_ROUNDS} rounds.`);
203
+ });
204
+ } },
205
+ html,
206
+ settle,
207
+ async rerender(next) {
208
+ if (unmounted) throw new Error("rerender: the view is unmounted.");
209
+ const props = checkProps("rerender", next) ?? {};
210
+ report(await instance.rerender(props));
211
+ await step(`rerender ${JSON.stringify(props)}`);
212
+ },
213
+ emitted(name) {
214
+ if (!declaredNames.includes(name)) throw new Error(`view.emitted("${name}"): the component declares no event "${name}" (${declaredNames.length ? `it declares ${declaredNames.join(", ")}` : "it declares none"}).`);
215
+ return emittedArgs("view.emitted").filter((event) => event.name === name).map((event) => event.args);
216
+ },
217
+ events: () => emittedArgs("view.events").map((event) => [event.name, ...event.args]),
218
+ expectParity: (name, parityOptions) => expectParity({
219
+ ...view,
220
+ trace,
221
+ dom,
222
+ aria
223
+ }, name, parityOptions),
224
+ expectThrown: (action) => expectThrown({
225
+ settle: () => settleFrame(() => instance.settle()),
226
+ stepMark: () => trace.length,
227
+ forgetSteps: (mark) => trace.forget(mark)
228
+ }, action),
229
+ async unmount() {
230
+ if (unmounted) return;
231
+ unmounted = true;
232
+ mounted.delete(view);
233
+ try {
234
+ await instance.unmount();
235
+ } finally {
236
+ container.remove();
237
+ }
238
+ }
239
+ };
240
+ mounted.add(view);
241
+ if (!await settleUntilQuiet()) throw new Error(`mount: the component did not settle: its DOM or its events still changed after ${SETTLE_ROUNDS} rounds. A component that keeps changing on its own (a timer) starts from an action, after the first expectParity (ADR-0050).`);
242
+ return view;
243
+ }
244
+ /** Records an L9 failure on the current test: a step that never settled cannot be compared. */
245
+ function failTrace(target, message) {
246
+ const test = TestRunner.getCurrentTest();
247
+ if (!test) throw new Error(message);
248
+ const harness = inject("ufHarness");
249
+ recordLayer(test, {
250
+ case: caseOfFile(test.file.filepath, harness),
251
+ target,
252
+ quarantine: harness.quarantine
253
+ }, "L9", {
254
+ status: "fail",
255
+ message: `${message}: the DOM or the emitted events still changed after ${SETTLE_ROUNDS} rounds of settling.`
256
+ });
257
+ }
258
+ /** Hands what a render logged outside the page (Astro's server render) to the L13 capture. */
259
+ function report(rendered) {
260
+ if (rendered && rendered.console?.length) captureExternalConsole(rendered.console);
261
+ }
262
+ /** The props an adapter gets: a plain object, or none. */
263
+ function checkProps(action, props) {
264
+ if (props === void 0 || isProps(props)) return props;
265
+ throw new TypeError(`${action}: props are an object of prop names and values, not ${props === null ? "null" : Array.isArray(props) ? "an array" : typeof props}.`);
266
+ }
267
+ function isProps(value) {
268
+ return typeof value === "object" && value !== null && !Array.isArray(value);
269
+ }
270
+ /** Unmounts every view the current test left mounted, newest first. */
271
+ async function cleanup() {
272
+ const errors = [];
273
+ for (const view of [...mounted].reverse()) try {
274
+ await view.unmount();
275
+ } catch (error) {
276
+ errors.push(error);
277
+ }
278
+ if (errors.length === 1) throw errors[0];
279
+ if (errors.length) throw new AggregateError(errors, `${errors.length} views failed to unmount.`);
280
+ }
281
+ //#endregion
282
+ export { cleanup, mount, mountScenario };
@@ -0,0 +1,20 @@
1
+ import { CaptureRequest, CaptureResult, PixelTolerance } from "../visual-types.js";
2
+ import "../commands.js";
3
+ import { RunnerTestCase } from "vitest";
4
+ import { Locator } from "vitest/browser";
5
+ //#region src/browser/visual.d.ts
6
+ /** Sends a capture to Node: `ufVisualCapture` for a case, or another package's own command. */
7
+ export type CaptureCommand = (request: CaptureRequest) => Promise<CaptureResult>;
8
+ /**
9
+ * Captures a settled container and compares it under the run's policy. `send` is the command
10
+ * that locates and compares it: the corpus's `ufVisualCapture` by default, or the visual
11
+ * runner's for an example (ADR-0087).
12
+ */
13
+ export declare function captureVisual(test: RunnerTestCase, input: {
14
+ case: string;
15
+ name: string;
16
+ container: HTMLElement;
17
+ locator: Locator;
18
+ tolerance?: PixelTolerance;
19
+ }, send?: CaptureCommand): Promise<CaptureResult>;
20
+ //#endregion
@@ -0,0 +1,36 @@
1
+ import { captureGeometry } from "./geometry.js";
2
+ import { withMergedTextRuns } from "./text-runs.js";
3
+ import { recordArtifact } from "vitest";
4
+ import { commands } from "vitest/browser";
5
+ //#region src/browser/visual.ts
6
+ let markers = 0;
7
+ /**
8
+ * Captures a settled container and compares it under the run's policy. `send` is the command
9
+ * that locates and compares it: the corpus's `ufVisualCapture` by default, or the visual
10
+ * runner's for an example (ADR-0087).
11
+ */
12
+ async function captureVisual(test, input, send = (request) => commands.ufVisualCapture(request)) {
13
+ const marker = `${Date.now().toString(36)}-${markers += 1}`;
14
+ input.container.setAttribute("data-uf-capture", marker);
15
+ try {
16
+ const result = await withMergedTextRuns(input.container, () => send({
17
+ element: input.locator.serialize(),
18
+ case: input.case,
19
+ name: input.name,
20
+ geometry: captureGeometry(input.container),
21
+ marker,
22
+ ...input.tolerance ? { tolerance: input.tolerance } : {}
23
+ }));
24
+ if (!result.pass && result.attachments.length) await recordArtifact(test, {
25
+ type: "internal:toMatchScreenshot",
26
+ kind: "visual-regression",
27
+ message: result.message,
28
+ attachments: result.attachments
29
+ });
30
+ return result;
31
+ } finally {
32
+ input.container.removeAttribute("data-uf-capture");
33
+ }
34
+ }
35
+ //#endregion
36
+ export { captureVisual };