@zerolith/test 0.0.0-stage → 0.1.0-alpha.2

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,33 @@
1
- # Temporary Holding Version
1
+ # @zerolith/test
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Test helpers for zerolith applications, independent of the test runner.
4
+
5
+ ```ts
6
+ import { afterEach, expect, it } from "vitest";
7
+ import { accessibilityIssues, cleanup, hydrationMismatches, mount, settle } from "@zerolith/test";
8
+
9
+ afterEach(cleanup);
10
+
11
+ it("renders and hydrates", async () =>
12
+ {
13
+ const { container } = mount(Counter());
14
+ container.querySelector("button")?.click();
15
+ await settle();
16
+ expect(container.textContent).toContain("1");
17
+ expect(hydrationMismatches(() => Counter())).toEqual([]);
18
+ expect(accessibilityIssues(container)).toEqual([]);
19
+ });
20
+ ```
21
+
22
+ - `mount` renders a view into a container attached to the document and remembers it; `cleanup` disposes everything mounted, in reverse order.
23
+ - `settle` waits for the promises a test started, such as resources and lazy routes; effects themselves run synchronously.
24
+ - `hydrationMismatches` renders a view with the server renderer, hydrates the same view over that markup, and returns every disagreement, so a component that cannot hydrate fails its test.
25
+ - `accessibilityIssues` finds the defects a test can catch without a browser engine's accessibility tree: images without alternative text, controls without a label, buttons and links without a name, frames without a title.
26
+
27
+ The guide is on the [docs site](https://molexxxx.github.io/zerolith/guide/testing/).
28
+
29
+ Status: alpha. Install with `npm install --save-dev @zerolith/test@alpha`; the API may change before 1.0.
30
+
31
+ ## License
32
+
33
+ Apache-2.0. See `LICENSE`.
@@ -0,0 +1,53 @@
1
+ /**
2
+ * @zerolith/test: helpers for testing zerolith views in any runner that
3
+ * gives them a DOM. Mount with automatic cleanup, settle async work, check
4
+ * a view's server markup against hydration, and find the accessibility
5
+ * defects a test can catch.
6
+ */
7
+ import { type HydrationMismatch, type Root } from "zerolith";
8
+ /** What `mount` returns. */
9
+ export interface Mounted {
10
+ /** The element the view was rendered into. */
11
+ readonly container: HTMLElement;
12
+ readonly root: Root;
13
+ /** Disposes the view and removes the container; `cleanup` does the same for every mount. */
14
+ unmount(): void;
15
+ }
16
+ /** Options for `mount`. */
17
+ export interface MountOptions {
18
+ /** Renders into this element instead of a new `div`. */
19
+ container?: HTMLElement;
20
+ /** Appends a new container to `document.body`. Defaults to true; layout and focus need it. */
21
+ attach?: boolean;
22
+ }
23
+ /** Renders a view into a container and remembers it for `cleanup`. */
24
+ export declare function mount(view: unknown, options?: MountOptions): Mounted;
25
+ /** Unmounts everything `mount` created, newest first. Register it as the runner's after-each hook. */
26
+ export declare function cleanup(): void;
27
+ /**
28
+ * Waits for the asynchronous work a test started: resources, lazy routes,
29
+ * and anything scheduled with promises or a timer of zero. Effects run
30
+ * synchronously when a signal changes, so they need no settling.
31
+ */
32
+ export declare function settle(rounds?: number): Promise<void>;
33
+ /**
34
+ * Renders `view()` with the server renderer, hydrates a second `view()` over
35
+ * that markup, and returns every disagreement. An empty array means the
36
+ * component hydrates cleanly; the container is discarded afterwards.
37
+ */
38
+ export declare function hydrationMismatches(view: () => unknown): HydrationMismatch[];
39
+ /** The accessibility checks `accessibilityIssues` runs. */
40
+ export type AccessibilityCode = "image_without_alt" | "control_without_label" | "button_without_name" | "link_without_name" | "frame_without_title";
41
+ /** One defect found by `accessibilityIssues`. */
42
+ export interface AccessibilityIssue {
43
+ readonly code: AccessibilityCode;
44
+ readonly element: Element;
45
+ }
46
+ /**
47
+ * Finds the defects that need no accessibility tree to detect, the ones the
48
+ * WebAIM Million finds on most home pages: images without `alt`, form
49
+ * controls without a label, buttons and links without an accessible name,
50
+ * and frames without a title. It is a floor, not a conformance check.
51
+ */
52
+ export declare function accessibilityIssues(container: ParentNode): AccessibilityIssue[];
53
+ //# sourceMapping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/index.js ADDED
@@ -0,0 +1,116 @@
1
+ /**
2
+ * @zerolith/test: helpers for testing zerolith views in any runner that
3
+ * gives them a DOM. Mount with automatic cleanup, settle async work, check
4
+ * a view's server markup against hydration, and find the accessibility
5
+ * defects a test can catch.
6
+ */
7
+ import { hydrate, render } from "zerolith";
8
+ import { renderToString } from "zerolith/ssr";
9
+ const mounted = [];
10
+ /** Renders a view into a container and remembers it for `cleanup`. */
11
+ export function mount(view, options = {}) {
12
+ const container = options.container ?? document.createElement("div");
13
+ if (options.container === undefined && options.attach !== false) {
14
+ document.body.append(container);
15
+ }
16
+ const root = render(view, container);
17
+ const entry = {
18
+ container,
19
+ root,
20
+ unmount() {
21
+ const index = mounted.indexOf(entry);
22
+ if (index !== -1) {
23
+ mounted.splice(index, 1);
24
+ }
25
+ root.dispose();
26
+ if (options.container === undefined) {
27
+ container.remove();
28
+ }
29
+ }
30
+ };
31
+ mounted.push(entry);
32
+ return entry;
33
+ }
34
+ /** Unmounts everything `mount` created, newest first. Register it as the runner's after-each hook. */
35
+ export function cleanup() {
36
+ for (const entry of mounted.toReversed()) {
37
+ entry.unmount();
38
+ }
39
+ }
40
+ /**
41
+ * Waits for the asynchronous work a test started: resources, lazy routes,
42
+ * and anything scheduled with promises or a timer of zero. Effects run
43
+ * synchronously when a signal changes, so they need no settling.
44
+ */
45
+ export function settle(rounds = 2) {
46
+ let chain = Promise.resolve();
47
+ for (let round = 0; round < rounds; round++) {
48
+ chain = chain.then(() => new Promise((resolve) => setTimeout(resolve, 0)));
49
+ }
50
+ return chain;
51
+ }
52
+ /**
53
+ * Renders `view()` with the server renderer, hydrates a second `view()` over
54
+ * that markup, and returns every disagreement. An empty array means the
55
+ * component hydrates cleanly; the container is discarded afterwards.
56
+ */
57
+ export function hydrationMismatches(view) {
58
+ const container = document.createElement("div");
59
+ container.innerHTML = renderToString(view());
60
+ const result = hydrate(view(), container);
61
+ const mismatches = [...result.mismatches];
62
+ result.dispose();
63
+ return mismatches;
64
+ }
65
+ function hasName(element) {
66
+ const label = element.getAttribute("aria-label") ?? "";
67
+ if (label.trim() !== "" || element.hasAttribute("aria-labelledby") || (element.getAttribute("title") ?? "").trim() !== "") {
68
+ return true;
69
+ }
70
+ if ((element.textContent ?? "").trim() !== "") {
71
+ return true;
72
+ }
73
+ return [...element.querySelectorAll("img[alt]")].some((image) => (image.getAttribute("alt") ?? "").trim() !== "");
74
+ }
75
+ function isLabeled(control) {
76
+ if (hasName(control) || control.closest("label") !== null) {
77
+ return true;
78
+ }
79
+ const id = control.getAttribute("id");
80
+ return id !== null && id !== "" && control.ownerDocument.querySelector(`label[for="${CSS.escape(id)}"]`) !== null;
81
+ }
82
+ /**
83
+ * Finds the defects that need no accessibility tree to detect, the ones the
84
+ * WebAIM Million finds on most home pages: images without `alt`, form
85
+ * controls without a label, buttons and links without an accessible name,
86
+ * and frames without a title. It is a floor, not a conformance check.
87
+ */
88
+ export function accessibilityIssues(container) {
89
+ const issues = [];
90
+ for (const image of container.querySelectorAll("img:not([alt])")) {
91
+ issues.push({ code: "image_without_alt", element: image });
92
+ }
93
+ for (const control of container.querySelectorAll("input:not([type=hidden]):not([type=submit]):not([type=button]):not([type=reset]):not([type=image]), select, textarea")) {
94
+ if (!isLabeled(control)) {
95
+ issues.push({ code: "control_without_label", element: control });
96
+ }
97
+ }
98
+ for (const button of container.querySelectorAll("button, input[type=submit], input[type=button], input[type=reset], input[type=image], [role=button]")) {
99
+ const named = button instanceof HTMLInputElement ? (button.value.trim() !== "" || (button.getAttribute("alt") ?? "").trim() !== "" || hasName(button)) : hasName(button);
100
+ if (!named) {
101
+ issues.push({ code: "button_without_name", element: button });
102
+ }
103
+ }
104
+ for (const anchor of container.querySelectorAll("a[href]")) {
105
+ if (!hasName(anchor)) {
106
+ issues.push({ code: "link_without_name", element: anchor });
107
+ }
108
+ }
109
+ for (const frame of container.querySelectorAll("iframe")) {
110
+ if ((frame.getAttribute("title") ?? "").trim() === "") {
111
+ issues.push({ code: "frame_without_title", element: frame });
112
+ }
113
+ }
114
+ return issues;
115
+ }
116
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAqC,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAC9E,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAqB9C,MAAM,OAAO,GAAc,EAAE,CAAC;AAE9B,sEAAsE;AACtE,MAAM,UAAU,KAAK,CAAC,IAAa,EAAE,OAAO,GAAiB,EAAE;IAE3D,MAAM,SAAS,GAAG,OAAO,CAAC,SAAS,IAAI,QAAQ,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC;IACrE,IAAI,OAAO,CAAC,SAAS,KAAK,SAAS,IAAI,OAAO,CAAC,MAAM,KAAK,KAAK,EAC/D,CAAC;QACG,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IACpC,CAAC;IACD,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC,CAAC;IACrC,MAAM,KAAK,GAAY;QACnB,SAAS;QACT,IAAI;QACJ,OAAO;YAEH,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YACrC,IAAI,KAAK,KAAK,CAAC,CAAC,EAChB,CAAC;gBACG,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;YAC7B,CAAC;YACD,IAAI,CAAC,OAAO,EAAE,CAAC;YACf,IAAI,OAAO,CAAC,SAAS,KAAK,SAAS,EACnC,CAAC;gBACG,SAAS,CAAC,MAAM,EAAE,CAAC;YACvB,CAAC;QACL,CAAC;KACJ,CAAC;IACF,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACpB,OAAO,KAAK,CAAC;AACjB,CAAC;AAED,sGAAsG;AACtG,MAAM,UAAU,OAAO;IAE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L,CAAC;IACD,OAAO,MAAM,CAAC;AAClB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
- "name": "@zerolith/test",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@zerolith/test",
3
+ "version": "0.1.0-alpha.2",
4
+ "description": "Test helpers for zerolith: mount views with automatic cleanup, settle async work, check a view's server markup against hydration, and find the accessibility defects a test can catch",
5
+ "license": "Apache-2.0",
6
+ "author": "molexxxx",
7
+ "homepage": "https://github.com/molexxxx/zerolith#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/molexxxx/zerolith.git",
11
+ "directory": "packages/test"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/molexxxx/zerolith/issues"
15
+ },
16
+ "keywords": [
17
+ "zerolith",
18
+ "testing",
19
+ "hydration",
20
+ "accessibility"
21
+ ],
22
+ "type": "module",
23
+ "sideEffects": false,
24
+ "engines": {
25
+ "node": ">=24.0.0"
26
+ },
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "default": "./dist/index.js"
31
+ },
32
+ "./package.json": "./package.json"
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "src",
37
+ "LICENSE",
38
+ "README.md"
39
+ ],
40
+ "scripts": {
41
+ "build": "tsc -p tsconfig.build.json"
42
+ },
43
+ "peerDependencies": {
44
+ "zerolith": "^0.1.0-alpha.2"
45
+ },
46
+ "devDependencies": {
47
+ "zerolith": "^0.1.0-alpha.2"
48
+ }
49
+ }
package/src/index.ts ADDED
@@ -0,0 +1,177 @@
1
+ /**
2
+ * @zerolith/test: helpers for testing zerolith views in any runner that
3
+ * gives them a DOM. Mount with automatic cleanup, settle async work, check
4
+ * a view's server markup against hydration, and find the accessibility
5
+ * defects a test can catch.
6
+ */
7
+ import { type HydrationMismatch, type Root, hydrate, render } from "zerolith";
8
+ import { renderToString } from "zerolith/ssr";
9
+
10
+ /** What `mount` returns. */
11
+ export interface Mounted
12
+ {
13
+ /** The element the view was rendered into. */
14
+ readonly container: HTMLElement;
15
+ readonly root: Root;
16
+ /** Disposes the view and removes the container; `cleanup` does the same for every mount. */
17
+ unmount(): void;
18
+ }
19
+
20
+ /** Options for `mount`. */
21
+ export interface MountOptions
22
+ {
23
+ /** Renders into this element instead of a new `div`. */
24
+ container?: HTMLElement;
25
+ /** Appends a new container to `document.body`. Defaults to true; layout and focus need it. */
26
+ attach?: boolean;
27
+ }
28
+
29
+ const mounted: Mounted[] = [];
30
+
31
+ /** Renders a view into a container and remembers it for `cleanup`. */
32
+ export function mount(view: unknown, options: MountOptions = {}): Mounted
33
+ {
34
+ const container = options.container ?? document.createElement("div");
35
+ if (options.container === undefined && options.attach !== false)
36
+ {
37
+ document.body.append(container);
38
+ }
39
+ const root = render(view, container);
40
+ const entry: Mounted = {
41
+ container,
42
+ root,
43
+ unmount(): void
44
+ {
45
+ const index = mounted.indexOf(entry);
46
+ if (index !== -1)
47
+ {
48
+ mounted.splice(index, 1);
49
+ }
50
+ root.dispose();
51
+ if (options.container === undefined)
52
+ {
53
+ container.remove();
54
+ }
55
+ }
56
+ };
57
+ mounted.push(entry);
58
+ return entry;
59
+ }
60
+
61
+ /** Unmounts everything `mount` created, newest first. Register it as the runner's after-each hook. */
62
+ export function cleanup(): void
63
+ {
64
+ for (const entry of mounted.toReversed())
65
+ {
66
+ entry.unmount();
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Waits for the asynchronous work a test started: resources, lazy routes,
72
+ * and anything scheduled with promises or a timer of zero. Effects run
73
+ * synchronously when a signal changes, so they need no settling.
74
+ */
75
+ export function settle(rounds = 2): Promise<void>
76
+ {
77
+ let chain = Promise.resolve();
78
+ for (let round = 0; round < rounds; round++)
79
+ {
80
+ chain = chain.then(() => new Promise<void>((resolve) => setTimeout(resolve, 0)));
81
+ }
82
+ return chain;
83
+ }
84
+
85
+ /**
86
+ * Renders `view()` with the server renderer, hydrates a second `view()` over
87
+ * that markup, and returns every disagreement. An empty array means the
88
+ * component hydrates cleanly; the container is discarded afterwards.
89
+ */
90
+ export function hydrationMismatches(view: () => unknown): HydrationMismatch[]
91
+ {
92
+ const container = document.createElement("div");
93
+ container.innerHTML = renderToString(view());
94
+ const result = hydrate(view(), container);
95
+ const mismatches = [...result.mismatches];
96
+ result.dispose();
97
+ return mismatches;
98
+ }
99
+
100
+ /** The accessibility checks `accessibilityIssues` runs. */
101
+ export type AccessibilityCode = "image_without_alt" | "control_without_label" | "button_without_name" | "link_without_name" | "frame_without_title";
102
+
103
+ /** One defect found by `accessibilityIssues`. */
104
+ export interface AccessibilityIssue
105
+ {
106
+ readonly code: AccessibilityCode;
107
+ readonly element: Element;
108
+ }
109
+
110
+ function hasName(element: Element): boolean
111
+ {
112
+ const label = element.getAttribute("aria-label") ?? "";
113
+ if (label.trim() !== "" || element.hasAttribute("aria-labelledby") || (element.getAttribute("title") ?? "").trim() !== "")
114
+ {
115
+ return true;
116
+ }
117
+ if ((element.textContent ?? "").trim() !== "")
118
+ {
119
+ return true;
120
+ }
121
+ return [...element.querySelectorAll("img[alt]")].some((image) => (image.getAttribute("alt") ?? "").trim() !== "");
122
+ }
123
+
124
+ function isLabeled(control: Element): boolean
125
+ {
126
+ if (hasName(control) || control.closest("label") !== null)
127
+ {
128
+ return true;
129
+ }
130
+ const id = control.getAttribute("id");
131
+ return id !== null && id !== "" && control.ownerDocument.querySelector(`label[for="${CSS.escape(id)}"]`) !== null;
132
+ }
133
+
134
+ /**
135
+ * Finds the defects that need no accessibility tree to detect, the ones the
136
+ * WebAIM Million finds on most home pages: images without `alt`, form
137
+ * controls without a label, buttons and links without an accessible name,
138
+ * and frames without a title. It is a floor, not a conformance check.
139
+ */
140
+ export function accessibilityIssues(container: ParentNode): AccessibilityIssue[]
141
+ {
142
+ const issues: AccessibilityIssue[] = [];
143
+ for (const image of container.querySelectorAll("img:not([alt])"))
144
+ {
145
+ issues.push({ code: "image_without_alt", element: image });
146
+ }
147
+ for (const control of container.querySelectorAll("input:not([type=hidden]):not([type=submit]):not([type=button]):not([type=reset]):not([type=image]), select, textarea"))
148
+ {
149
+ if (!isLabeled(control))
150
+ {
151
+ issues.push({ code: "control_without_label", element: control });
152
+ }
153
+ }
154
+ for (const button of container.querySelectorAll("button, input[type=submit], input[type=button], input[type=reset], input[type=image], [role=button]"))
155
+ {
156
+ const named = button instanceof HTMLInputElement ? (button.value.trim() !== "" || (button.getAttribute("alt") ?? "").trim() !== "" || hasName(button)) : hasName(button);
157
+ if (!named)
158
+ {
159
+ issues.push({ code: "button_without_name", element: button });
160
+ }
161
+ }
162
+ for (const anchor of container.querySelectorAll("a[href]"))
163
+ {
164
+ if (!hasName(anchor))
165
+ {
166
+ issues.push({ code: "link_without_name", element: anchor });
167
+ }
168
+ }
169
+ for (const frame of container.querySelectorAll("iframe"))
170
+ {
171
+ if ((frame.getAttribute("title") ?? "").trim() === "")
172
+ {
173
+ issues.push({ code: "frame_without_title", element: frame });
174
+ }
175
+ }
176
+ return issues;
177
+ }