@uniflowed/test 0.0.0-alpha.4 → 0.0.0-alpha.40

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.
@@ -11,10 +11,66 @@
11
11
  // `.resolves` and `.rejects` settle the promise first and then apply the same
12
12
  // matcher table to what came out, so `await expect(p).resolves.toBe(1)` reads
13
13
  // the way the synchronous form does.
14
+ //
15
+ // # The names are written down, and the behaviour is not
16
+ //
17
+ // `expect` used to be `$FlowFixMe`, and so was everything it handed back. That
18
+ // is a hole in the published type of the package a project writes every one of
19
+ // its assertions against: `expect(user).toBaa(1)` was not a misspelling
20
+ // anybody's checker would find, `expect(list).toHaveLength("3")` was not a type
21
+ // error, and `expect(p).resolves` on a value that is not a promise was fine
22
+ // until it ran. Every test in this repository is written against `expect`,
23
+ // which is the largest surface in the packages and was the least checked.
24
+ //
25
+ // So [`Matchers`] below writes the names out, one signature per matcher, the
26
+ // way `@uniflowed/react-testing`'s `Queries` writes out its thirty-six. Flow
27
+ // has no template literal types and no way to read a name out of a value, so
28
+ // the listing has to exist for the type to exist at all. What is *not*
29
+ // repeated is any behaviour: [`verdicts`] is still the one place a matcher is
30
+ // decided, and the listing is a naming that a reader can check against it by
31
+ // eye.
32
+ //
33
+ // [`Matchers`] is generic in what a matcher *returns*, which is what lets
34
+ // `.resolves` reuse the one listing: the same forty-one names, each handing
35
+ // back a promise.
36
+ //
37
+ // # The received value's type is not carried, and that was tried
38
+ //
39
+ // ubugeeei-prod/uf#402 asked for a second parameter as well — the type handed
40
+ // to `expect`, carried through the matchers so that `expect(count).toBe("two")`
41
+ // is an error at the call. It is written here rather than left for somebody to
42
+ // discover, because it looks obviously right and is not.
43
+ //
44
+ // `toBe` is `Object.is`, and identity is not assignability. Typing it
45
+ // `(expected: T)` demands that the expected value be a subtype of the received
46
+ // one, which is a direction the runtime has no opinion about and which ordinary
47
+ // assertions fail in both:
48
+ // `expect(document.activeElement).toBe(screen.getByRole("button"))` compares an
49
+ // `HTMLElement | null` with an `Element`, neither is the other's subtype, and
50
+ // that is the most common assertion in a DOM test. Jest and Vitest both type
51
+ // this argument as `unknown` for the same reason.
52
+ //
53
+ // Worse, the parameter has to be *inferred*, and `expect(x)` is where a lot of
54
+ // otherwise unconstrained expressions sit. `await
55
+ // expect(client.request("/users/1")).resolves.toEqual({ id: 1 })` stops
56
+ // checking and starts reporting that `request`'s own type parameter is
57
+ // underconstrained, because a `mixed` parameter asked nothing of the argument
58
+ // and a generic one asks it to be solved. `expect([])` becomes "cannot
59
+ // determine type of empty array literal". Both are correct tests, and the type
60
+ // that rejects them is worse than the type that missed a mistyped comparison.
61
+ //
62
+ // So the received value arrives as `mixed`, and what makes a matcher checked is
63
+ // its own signature: `toHaveLength` wants a number, `toMatch` a pattern,
64
+ // `toBeTypeOf` one of the eight words `typeof` answers with, and every name is
65
+ // a name. The comparison between two unrelated types stays unchecked, and it is
66
+ // the only part of the issue that does.
14
67
 
68
+ import type { AsymmetricMatcher } from "./asymmetric.js";
69
+ import type { AxeOptions } from "./axe.js";
15
70
  import type { SpyCall } from "./spy.js";
16
71
  import * as asymmetric from "./asymmetric.js";
17
72
  import * as snapshot from "./snapshot.js";
73
+ import { auditElement, describeViolations, violationIds } from "./axe.js";
18
74
  import { isSpy } from "./spy.js";
19
75
  import { equals, matchesObject, render } from "./equality.js";
20
76
 
@@ -36,7 +92,14 @@ export class AssertionError extends Error {
36
92
  }
37
93
  }
38
94
 
39
- /** What a matcher decided, and how to say it either way. */
95
+ /**
96
+ * What a matcher decided, and how to say it either way.
97
+ *
98
+ * A matcher may answer with a promise of one. Only one does — the accessibility
99
+ * audit, whose engine has no synchronous entry point — and [`bind`] is where
100
+ * the two cases are told apart; see the note there for why the promise is not
101
+ * hidden from the caller.
102
+ */
40
103
  type Verdict = {|
41
104
  readonly pass: boolean,
42
105
  readonly failure: () => string,
@@ -45,6 +108,166 @@ type Verdict = {|
45
108
  readonly received?: string,
46
109
  |};
47
110
 
111
+ /** What `typeof` can answer, for the matcher that compares against it. */
112
+ type TypeName =
113
+ | "bigint"
114
+ | "boolean"
115
+ | "function"
116
+ | "number"
117
+ | "object"
118
+ | "string"
119
+ | "symbol"
120
+ | "undefined";
121
+
122
+ /**
123
+ * Every matcher, each returning `R`.
124
+ *
125
+ * Generic in the return type because the surface exists twice and that is the
126
+ * only thing that differs: `expect(x)` raises where a matcher fails and hands
127
+ * back nothing, while `expect(p).resolves` settles first and so hands back a
128
+ * promise. Writing the forty-one names once and saying what changes is the
129
+ * whole reason for the parameter — the alternative was the same list twice,
130
+ * with `=> void` on one copy and `=> Promise<void>` on the other, and a reader
131
+ * left to diff them.
132
+ *
133
+ * Where an argument is `mixed` it is because the runtime genuinely takes
134
+ * anything there and the checker would be lying to say otherwise: `toEqual`
135
+ * accepts an asymmetric matcher standing in for a value at any depth, and
136
+ * `toHaveValue` compares whatever a control is holding. Where it is not —
137
+ * `toHaveLength` wants a number, `toMatch` a string or a pattern, `toBeTypeOf`
138
+ * one of the eight words `typeof` produces — the narrower type is what the
139
+ * implementation already assumes, and saying it out loud is the point of the
140
+ * exercise.
141
+ *
142
+ * `not` is the same list again because negation is the only thing it changes.
143
+ * `resolves` and `rejects` are deliberately not here: they belong to
144
+ * [`Expectation`], because `expect(p).resolves.not` exists and
145
+ * `expect(x).not.resolves` does not.
146
+ */
147
+ export type Matchers<R> = {
148
+ readonly toBe: (expected: mixed) => R,
149
+ readonly toEqual: (expected: mixed) => R,
150
+ readonly toStrictEqual: (expected: mixed) => R,
151
+ readonly toBeTruthy: () => R,
152
+ readonly toBeFalsy: () => R,
153
+ readonly toBeNull: () => R,
154
+ readonly toBeUndefined: () => R,
155
+ readonly toBeDefined: () => R,
156
+ readonly toBeNaN: () => R,
157
+ readonly toBeGreaterThan: (expected: number) => R,
158
+ readonly toBeGreaterThanOrEqual: (expected: number) => R,
159
+ readonly toBeLessThan: (expected: number) => R,
160
+ readonly toBeLessThanOrEqual: (expected: number) => R,
161
+ readonly toBeCloseTo: (expected: number, digits?: number) => R,
162
+ readonly toContain: (expected: mixed) => R,
163
+ readonly toContainEqual: (expected: mixed) => R,
164
+ readonly toHaveLength: (expected: number) => R,
165
+ readonly toHaveProperty: (path: string, ...rest: $ReadOnlyArray<mixed>) => R,
166
+ readonly toMatch: (expected: string | RegExp) => R,
167
+ readonly toMatchObject: (expected: mixed) => R,
168
+ readonly toBeInstanceOf: (expected: mixed) => R,
169
+ readonly toBeTypeOf: (expected: TypeName) => R,
170
+ readonly toSatisfy: (predicate: (value: mixed) => boolean) => R,
171
+ readonly toMatchSnapshot: (hint?: string) => R,
172
+ readonly toMatchInlineSnapshot: (expected?: string) => R,
173
+ readonly toThrow: (...rest: $ReadOnlyArray<mixed>) => R,
174
+ readonly toHaveBeenCalled: () => R,
175
+ readonly toHaveBeenCalledTimes: (count: number) => R,
176
+ readonly toHaveBeenCalledWith: (...args: $ReadOnlyArray<mixed>) => R,
177
+ readonly toHaveBeenLastCalledWith: (...args: $ReadOnlyArray<mixed>) => R,
178
+ readonly toBeInTheDocument: () => R,
179
+ readonly toBeVisible: () => R,
180
+ readonly toBeDisabled: () => R,
181
+ readonly toBeEnabled: () => R,
182
+ readonly toBeChecked: () => R,
183
+ readonly toBeRequired: () => R,
184
+ readonly toHaveFocus: () => R,
185
+ readonly toHaveAttribute: (name: string, value?: mixed) => R,
186
+ readonly toHaveClass: (...names: $ReadOnlyArray<string>) => R,
187
+ readonly toHaveTextContent: (expected: string | RegExp) => R,
188
+ readonly toHaveValue: (expected: mixed) => R,
189
+ /**
190
+ * Run axe-core over this element's subtree and require it to find nothing.
191
+ *
192
+ * `Promise<void>` rather than `R`, and it is the one matcher in this listing
193
+ * that is not generic: axe has no synchronous entry point, so the answer is
194
+ * a promise however the expectation was reached, and `await` is not optional.
195
+ *
196
+ * await expect(container).toHaveNoAxeViolations();
197
+ * await expect(container).toHaveNoAxeViolations({ tags: ["wcag2a"] });
198
+ *
199
+ * The rule set comes from `accessibility.axe` in `uf.config.js`; the argument
200
+ * narrows it for one assertion. See `./axe.js`.
201
+ */
202
+ readonly toHaveNoAxeViolations: (options?: AxeOptions) => Promise<void>,
203
+ readonly not: Matchers<R>,
204
+ ...
205
+ };
206
+
207
+ /**
208
+ * What `expect(received)` hands back.
209
+ *
210
+ * The matchers, plus the two that settle a promise before applying them. An
211
+ * intersection rather than a copy of the list with two lines added, and
212
+ * rather than an object spread, because a spread of an object type drops the
213
+ * `readonly` off every property it carries over — Flow computes a fresh object
214
+ * from the spread and the fresh one is writable, which would publish forty-one
215
+ * assignable matchers.
216
+ *
217
+ * # What is still not checked
218
+ *
219
+ * `expect(5).resolves` types, and fails when it runs. Saying otherwise needs
220
+ * `expect` to have two call signatures — one for a promise handing back a
221
+ * shape with `resolves`, one for everything else handing back a shape without
222
+ * — and Flow then requires the single function behind them to satisfy both,
223
+ * which no single function does. The overload is written down here rather than
224
+ * attempted because "it did not type" is the kind of thing that gets tried
225
+ * twice.
226
+ */
227
+ export type Expectation = Matchers<void> & {
228
+ readonly resolves: Matchers<Promise<void>>,
229
+ readonly rejects: Matchers<Promise<void>>,
230
+ ...
231
+ };
232
+
233
+ /**
234
+ * `expect` itself: callable, and carrying the matchers that stand in for a
235
+ * value instead of being one.
236
+ *
237
+ * Inexact, and it has to be. The value is a function, every function has
238
+ * `name`, `length`, `call`, `apply` and `bind`, and an exact object type
239
+ * refuses one for exactly that reason. Inexactness costs nothing that matters
240
+ * here: Flow still reports a read of a property this type does not list, which
241
+ * is what makes `expect.anythign()` an error.
242
+ */
243
+ export type Expect = {
244
+ (received: mixed): Expectation,
245
+ // `flow/unclear-type` reads source text rather than an AST, and the shape it
246
+ // recognises as a property key rather than a type is a name at the start of
247
+ // a line or straight after `{`, `,` or `;`. `readonly any:` is neither, so
248
+ // the rule reports Jest's, Vitest's and Sinon's name for this matcher as an
249
+ // `any` type. The rule's own comment already lists `@uniflowed/test`'s
250
+ // `expect.any` among the false positives it exists to avoid; this is the one
251
+ // spelling it still cannot see past.
252
+ // uf-lint-disable-next-line flow/unclear-type
253
+ readonly any: (constructor: mixed) => AsymmetricMatcher,
254
+ readonly anything: () => AsymmetricMatcher,
255
+ readonly objectContaining: (expected: interface {}) => AsymmetricMatcher,
256
+ readonly arrayContaining: (expected: $ReadOnlyArray<mixed>) => AsymmetricMatcher,
257
+ readonly stringContaining: (substring: string) => AsymmetricMatcher,
258
+ readonly stringMatching: (pattern: string | RegExp) => AsymmetricMatcher,
259
+ readonly closeTo: (value: number, digits?: number) => AsymmetricMatcher,
260
+ readonly not: {
261
+ readonly objectContaining: (expected: interface {}) => AsymmetricMatcher,
262
+ readonly arrayContaining: (expected: $ReadOnlyArray<mixed>) => AsymmetricMatcher,
263
+ readonly stringContaining: (substring: string) => AsymmetricMatcher,
264
+ readonly stringMatching: (pattern: string | RegExp) => AsymmetricMatcher,
265
+ readonly closeTo: (value: number, digits?: number) => AsymmetricMatcher,
266
+ ...
267
+ },
268
+ ...
269
+ };
270
+
48
271
  function propertyAt(
49
272
  value: mixed,
50
273
  path: string,
@@ -88,9 +311,37 @@ function matchesThrown(thrown: mixed, expected: mixed): boolean {
88
311
  *
89
312
  * Every entry returns a [`Verdict`] rather than throwing, which is what lets
90
313
  * `.not` reuse all of them.
314
+ *
315
+ * # Every entry takes `mixed`, and that is what makes the indexer sayable
316
+ *
317
+ * [`bind`] reaches an entry by a computed key and applies it to the
318
+ * `$ReadOnlyArray<mixed>` it collected from the caller, so the indexer has to
319
+ * describe a function that will accept those arguments. Parameters are
320
+ * contravariant, so an entry that demanded a `number` could not be described
321
+ * by one — `(...args: $ReadOnlyArray<mixed>)` rejects it, and
322
+ * `(...args: $ReadOnlyArray<empty>)` accepts it and rejects the call. That
323
+ * disagreement is why this indexer used to be written `$ReadOnlyArray<any>`,
324
+ * with a `flow/unclear-type` suppression on it.
325
+ *
326
+ * So the disagreement is gone instead of papered over: every entry here takes
327
+ * `mixed` and coerces what it needs, the way most of them — `toBe`,
328
+ * `toBeGreaterThan`, `toHaveAttribute` — already did. Nothing a caller can see
329
+ * got wider: `toHaveLength` still refuses a string and `toBeTypeOf` still
330
+ * refuses a word `typeof` never says, because those are [`Matchers`]'s
331
+ * signatures and [`Matchers`] is the published type. What changed is that the
332
+ * table behind them stopped claiming a narrower argument than the one `bind`
333
+ * can hand it, which is a claim that was never true. The `String(…)` and
334
+ * `Number(…)` calls that appeared with it are the coercion the runtime was
335
+ * already doing, said out loud, and each produces the same message the implicit
336
+ * one did for the same input.
337
+ *
338
+ * The alternative — narrowing the indexer by writing `bind`'s forty-one
339
+ * wrappers out to avoid the computed lookup — is a second copy of the listing
340
+ * to keep in step with [`Matchers`], and is a worse trade than either. See
341
+ * ubugeeei-prod/uf#402.
91
342
  */
92
343
  function verdicts(received: mixed): {
93
- readonly [string]: (...args: $ReadOnlyArray<any>) => Verdict,
344
+ readonly [string]: (...args: $ReadOnlyArray<mixed>) => Verdict | Promise<Verdict>,
94
345
  } {
95
346
  const shown = () => render(received);
96
347
  const simple = (pass: boolean, what: string, expected?: mixed): Verdict => ({
@@ -165,14 +416,15 @@ function verdicts(received: mixed): {
165
416
  `to be at most ${render(expected)}`,
166
417
  expected,
167
418
  ),
168
- toBeCloseTo: (expected: number, digits?: number) => {
169
- const places = digits ?? 2;
419
+ toBeCloseTo: (expected: mixed, digits?: mixed) => {
420
+ const target = Number(expected);
421
+ const places = digits === undefined ? 2 : Number(digits);
170
422
  const tolerance = 10 ** -places / 2;
171
- const difference = Math.abs((received as $FlowFixMe) - expected);
423
+ const difference = Math.abs((received as $FlowFixMe) - target);
172
424
  return simple(
173
425
  difference < tolerance,
174
- `to be within ${tolerance} of ${expected}, but it is off by ${difference}`,
175
- expected,
426
+ `to be within ${tolerance} of ${target}, but it is off by ${difference}`,
427
+ target,
176
428
  );
177
429
  },
178
430
  toContain: (expected: mixed) => {
@@ -198,22 +450,23 @@ function verdicts(received: mixed): {
198
450
  expected,
199
451
  );
200
452
  },
201
- toHaveLength: (expected: number) => {
453
+ toHaveLength: (expected: mixed) => {
202
454
  const length = received == null ? undefined : (received as $FlowFixMe).length;
203
455
  return simple(
204
456
  length === expected,
205
- `to have length ${expected}, not ${render(length)}`,
457
+ `to have length ${String(expected)}, not ${render(length)}`,
206
458
  expected,
207
459
  );
208
460
  },
209
- toHaveProperty: (path: string, ...rest: $ReadOnlyArray<mixed>) => {
210
- const found = propertyAt(received, path);
461
+ toHaveProperty: (path: mixed, ...rest: $ReadOnlyArray<mixed>) => {
462
+ const at = String(path);
463
+ const found = propertyAt(received, at);
211
464
  if (rest.length === 0) {
212
- return simple(found.found, `to have a property at \`${path}\``);
465
+ return simple(found.found, `to have a property at \`${at}\``);
213
466
  }
214
467
  return simple(
215
468
  found.found && equals(found.value, rest[0]),
216
- `to have \`${path}\` equal to ${render(rest[0])}, not ${render(found.value)}`,
469
+ `to have \`${at}\` equal to ${render(rest[0])}, not ${render(found.value)}`,
217
470
  rest[0],
218
471
  );
219
472
  },
@@ -233,16 +486,24 @@ function verdicts(received: mixed): {
233
486
  `to be an instance of ${render(expected)}`,
234
487
  expected,
235
488
  ),
236
- toBeTypeOf: (expected: string) =>
489
+ toBeTypeOf: (expected: mixed) => {
490
+ const name = String(expected);
491
+ return simple(
492
+ typeof received === name,
493
+ `to be of type ${name}, not ${typeof received}`,
494
+ name,
495
+ );
496
+ },
497
+ toSatisfy: (predicate: mixed) =>
237
498
  simple(
238
- typeof received === expected,
239
- `to be of type ${expected}, not ${typeof received}`,
240
- expected,
499
+ typeof predicate === "function" && predicate(received) === true,
500
+ "to satisfy the predicate",
241
501
  ),
242
- toSatisfy: (predicate: (value: mixed) => boolean) =>
243
- simple(predicate(received) === true, "to satisfy the predicate"),
244
- toMatchSnapshot: (hint?: string): Verdict => {
245
- const verdict = snapshot.matchSnapshot(received, hint);
502
+ toMatchSnapshot: (hint?: mixed): Verdict => {
503
+ const verdict = snapshot.matchSnapshot(
504
+ received,
505
+ hint === undefined ? undefined : String(hint),
506
+ );
246
507
  return {
247
508
  pass: verdict.pass,
248
509
  expected: verdict.expected ?? "(no snapshot yet)",
@@ -256,8 +517,11 @@ function verdicts(received: mixed): {
256
517
  negatedFailure: () => "expected the value not to match its snapshot",
257
518
  };
258
519
  },
259
- toMatchInlineSnapshot: (expected?: string): Verdict => {
260
- const verdict = snapshot.matchInlineSnapshot(received, expected);
520
+ toMatchInlineSnapshot: (expected?: mixed): Verdict => {
521
+ const verdict = snapshot.matchInlineSnapshot(
522
+ received,
523
+ expected === undefined ? undefined : String(expected),
524
+ );
261
525
  return {
262
526
  pass: verdict.pass,
263
527
  expected: verdict.expected ?? "(no inline snapshot yet)",
@@ -308,10 +572,14 @@ function verdicts(received: mixed): {
308
572
  requireSpy("toHaveBeenCalled");
309
573
  return simple(spyCalls().length > 0, "to have been called");
310
574
  },
311
- toHaveBeenCalledTimes: (count: number) => {
575
+ toHaveBeenCalledTimes: (count: mixed) => {
312
576
  requireSpy("toHaveBeenCalledTimes");
313
577
  const actual = spyCalls().length;
314
- return simple(actual === count, `to have been called ${count} times, not ${actual}`, count);
578
+ return simple(
579
+ actual === count,
580
+ `to have been called ${String(count)} times, not ${actual}`,
581
+ count,
582
+ );
315
583
  },
316
584
  toHaveBeenCalledWith: (...args: $ReadOnlyArray<mixed>) => {
317
585
  requireSpy("toHaveBeenCalledWith");
@@ -422,6 +690,23 @@ function verdicts(received: mixed): {
422
690
  failure: () => `expected the value ${render(actual)} to be ${render(expected)}`,
423
691
  };
424
692
  },
693
+ toHaveNoAxeViolations: async (options: mixed) => {
694
+ const node = element("toHaveNoAxeViolations");
695
+ const found = await auditElement(node, (options: $FlowFixMe));
696
+ const named = violationIds(found);
697
+ return {
698
+ pass: found.length === 0,
699
+ expected: "no accessibility violations",
700
+ received: found.length === 0 ? "none" : named,
701
+ failure: () =>
702
+ `expected no accessibility violations, and axe-core reported ` +
703
+ `${String(found.length)}:\n${describeViolations(found)}`,
704
+ // A passing audit is not proof of an accessible component — axe finds
705
+ // what a machine can find — so the negated message says what was
706
+ // actually established rather than implying the opposite verdict.
707
+ negatedFailure: () => "expected axe-core to report a violation, and it reported none",
708
+ };
709
+ },
425
710
  };
426
711
 
427
712
  /**
@@ -434,7 +719,16 @@ function verdicts(received: mixed): {
434
719
  function element(matcher: string): Element {
435
720
  const node: $FlowFixMe = received;
436
721
  if (node == null || typeof node.getAttribute !== "function") {
437
- throw new AssertionError(`${matcher} needs an element, and received ${render(received)}`);
722
+ // All four arguments, unlike the first version of this: the runner
723
+ // renders `expected` and `received` beside the message, and a one
724
+ // argument call left both of them `undefined` on screen for the one
725
+ // failure whose whole content is what was received instead.
726
+ throw new AssertionError(
727
+ `${matcher} needs an element, and received ${render(received)}`,
728
+ matcher,
729
+ "an element",
730
+ render(received),
731
+ );
438
732
  }
439
733
  return node;
440
734
  }
@@ -446,14 +740,42 @@ function verdicts(received: mixed): {
446
740
  * Walks the ancestors, because `display: none` on a parent hides a child whose
447
741
  * own style says nothing. `hidden`, `aria-hidden` and a `details` that is not
448
742
  * open each hide their subtree too.
743
+ *
744
+ * # The one thing a closed `<details>` still shows
745
+ *
746
+ * Its `<summary>`. A closed disclosure renders exactly one child and hides the
747
+ * rest, so the rule is "everything under a closed `<details>` except its
748
+ * summary" — and saying that needs the child the walk arrived from, not only
749
+ * the ancestor it is standing on. Without it the rule was written as "unless
750
+ * the `<details>` is the element being asked about", which exempted the
751
+ * disclosure from its own rule and left the summary inside it invisible:
752
+ * `expect(screen.getByText("More")).toBeVisible()` failed for the one thing on
753
+ * the screen, while the reader was looking at it.
754
+ *
755
+ * # Why this is not the walk in `react-testing`
756
+ *
757
+ * `packages/react-testing/internal/queries.js` has one that looks like this
758
+ * and answers a different question. `exposed` asks whether the accessibility
759
+ * tree announces the element, so it ignores `opacity: 0` — a screen reader
760
+ * reads text at zero opacity, which is exactly why hiding text that way is a
761
+ * bug rather than a technique — and it takes `aria-hidden` as decisive. This
762
+ * one asks whether a reader would *see* it, so the two answers part company
763
+ * there on purpose. The `<details>` half is the half they agree on, and it is
764
+ * written the same way in both.
449
765
  */
450
766
  function isVisible(node: Element): boolean {
767
+ let child: $FlowFixMe = null;
451
768
  let current: $FlowFixMe = node;
452
769
  while (current != null && current.nodeType === 1) {
453
770
  if (current.hasAttribute("hidden") || current.getAttribute("aria-hidden") === "true") {
454
771
  return false;
455
772
  }
456
- if (current.tagName === "DETAILS" && !current.hasAttribute("open") && current !== node) {
773
+ if (
774
+ child != null &&
775
+ current.tagName === "DETAILS" &&
776
+ !current.hasAttribute("open") &&
777
+ child.tagName !== "SUMMARY"
778
+ ) {
457
779
  return false;
458
780
  }
459
781
  const style = current.ownerDocument?.defaultView?.getComputedStyle?.(current);
@@ -465,6 +787,7 @@ function isVisible(node: Element): boolean {
465
787
  return false;
466
788
  }
467
789
  }
790
+ child = current;
468
791
  current = current.parentElement;
469
792
  }
470
793
  return true;
@@ -490,13 +813,23 @@ function isDisabled(node: Element): boolean {
490
813
  *
491
814
  * `negated` decides which message a failing verdict raises, which is all of
492
815
  * what `.not` is.
816
+ *
817
+ * # Why the object is built rather than written
818
+ *
819
+ * `.not` has to be reached lazily or building an expectation would build its
820
+ * negation, which would build *its* negation, forever. A lazily installed
821
+ * property is not something an object literal carries, so the value is
822
+ * completed with `Object.defineProperty` after it exists — and an object
823
+ * completed after the fact is not one Flow can check a literal against. That
824
+ * is what this `$FlowFixMe` is, and it now covers a construction rather than a
825
+ * published type: [`expectValue`] states the real one, and the checker holds
826
+ * every caller to it.
493
827
  */
494
828
  function bind(received: mixed, negated: boolean): $FlowFixMe {
495
829
  const table = verdicts(received);
496
830
  const bound: $FlowFixMe = {};
497
831
  for (const name of Object.keys(table)) {
498
- bound[name] = (...args: $ReadOnlyArray<mixed>) => {
499
- const verdict = table[name](...args);
832
+ const decide = (verdict: Verdict) => {
500
833
  if (verdict.pass !== negated) {
501
834
  return undefined;
502
835
  }
@@ -508,6 +841,29 @@ function bind(received: mixed, negated: boolean): $FlowFixMe {
508
841
  verdict.received ?? render(received),
509
842
  );
510
843
  };
844
+ bound[name] = (...args: $ReadOnlyArray<mixed>) => {
845
+ const verdict = table[name](...args);
846
+ // A matcher whose engine is asynchronous answers with a promise of a
847
+ // verdict, and the promise is handed straight back rather than hidden.
848
+ //
849
+ // Hiding it was the alternative and it cannot be done: the only way to
850
+ // present an asynchronous answer synchronously is to decide before it
851
+ // arrives, which is deciding without it. What the promise costs is a
852
+ // forgotten `await`, and that case is not silent either — the rejection
853
+ // reaches the worker's unhandled-rejection handler, which fails the file
854
+ // the promise was created in and prints this same message. A missing
855
+ // `await` on a passing audit is the one case nothing reports, and it is
856
+ // the case where nothing happened.
857
+ //
858
+ // `instanceof Promise` rather than a `then` test, and it is safe for a
859
+ // reason that would not survive being generalised: every entry in the
860
+ // table is written in this file, so the only promise that can arrive
861
+ // here is one an `async` function in this module made, in this realm. A
862
+ // matcher registered from outside — which `@uniflowed/test` has no API
863
+ // for, deliberately — could hand back a foreign thenable, and this line
864
+ // would be the thing to revisit.
865
+ return verdict instanceof Promise ? verdict.then(decide) : decide(verdict);
866
+ };
511
867
  }
512
868
  Object.defineProperty(bound, "not", { get: () => bind(received, !negated) });
513
869
  return bound;
@@ -555,7 +911,12 @@ function settled(promise: mixed, wanted: "resolve" | "reject", negated: boolean)
555
911
  throw value;
556
912
  }
557
913
  : value;
558
- bind(subject, negated)[name](...args);
914
+ // Returned rather than called and dropped: the wrapper is `async`, so
915
+ // returning an asynchronous matcher's promise is what awaits it. Without
916
+ // this, `await expect(p).resolves.toHaveNoAxeViolations()` awaited the
917
+ // settling and not the audit, and a violation surfaced as an unhandled
918
+ // rejection under whichever file was running by then.
919
+ return bind(subject, negated)[name](...args);
559
920
  };
560
921
  }
561
922
  Object.defineProperty(bound, "not", { get: () => settled(promise, wanted, !negated) });
@@ -571,8 +932,12 @@ function settled(promise: mixed, wanted: "resolve" | "reject", negated: boolean)
571
932
  * expect(() => parse("")).toThrow(/empty/);
572
933
  * await expect(load()).resolves.toHaveLength(3);
573
934
  * ```
935
+ *
936
+ * Takes a `mixed` and hands back a written-out [`Expectation`]. What each
937
+ * matcher will accept is decided by its own signature rather than by what was
938
+ * received, for the reasons this module's header sets out.
574
939
  */
575
- function expectValue(received: mixed): $FlowFixMe {
940
+ function expectValue(received: mixed): Expectation {
576
941
  const expectation: $FlowFixMe = bind(received, false);
577
942
  Object.defineProperty(expectation, "resolves", {
578
943
  get: () => settled(received, "resolve", false),
@@ -582,11 +947,45 @@ function expectValue(received: mixed): $FlowFixMe {
582
947
  }
583
948
 
584
949
  /**
585
- * Assert about a value.
950
+ * Build the callable that carries the asymmetric matchers.
951
+ *
952
+ * The statics are attached inside a builder rather than at the module's top
953
+ * level, the way `internal/registry.js` builds `describe`: a shipped module
954
+ * may only declare, import and export at its top level, and `expect.any = …`
955
+ * out here is a statement that runs when the module is imported.
586
956
  *
587
- * Declared with its matchers attached rather than assigned afterwards: a
588
- * shipped module may only declare, import and export at its top level, and
589
- * `expect.any = …` is a statement that runs when the module is imported.
957
+ * It was `Object.assign(expectValue, { … })`, which is what a reader expects
958
+ * and what does not type. Flow models `Object.assign` as returning the
959
+ * *target*, so the result of assigning matchers onto a function is still a
960
+ * function with no matchers on it — eight `prop-missing` errors saying so, and
961
+ * a `flow/unsafe-object-assign` suppression on top of them. Attaching to a
962
+ * local before it is returned is the same runtime value with none of that: the
963
+ * checker sees the statics arrive and holds the result to [`Expect`].
964
+ */
965
+ function expecting(): Expect {
966
+ const api = (received: mixed): Expectation => expectValue(received);
967
+ api.any = asymmetric.any;
968
+ api.anything = asymmetric.anything;
969
+ api.objectContaining = asymmetric.objectContaining;
970
+ api.arrayContaining = asymmetric.arrayContaining;
971
+ api.stringContaining = asymmetric.stringContaining;
972
+ api.stringMatching = asymmetric.stringMatching;
973
+ api.closeTo = asymmetric.closeTo;
974
+ api.not = {
975
+ objectContaining: (expected: interface {}) =>
976
+ asymmetric.not(asymmetric.objectContaining(expected)),
977
+ arrayContaining: (expected: $ReadOnlyArray<mixed>) =>
978
+ asymmetric.not(asymmetric.arrayContaining(expected)),
979
+ stringContaining: (substring: string) => asymmetric.not(asymmetric.stringContaining(substring)),
980
+ stringMatching: (pattern: string | RegExp) =>
981
+ asymmetric.not(asymmetric.stringMatching(pattern)),
982
+ closeTo: (value: number, digits?: number) => asymmetric.not(asymmetric.closeTo(value, digits)),
983
+ };
984
+ return api;
985
+ }
986
+
987
+ /**
988
+ * Assert about a value.
590
989
  *
591
990
  * The `expect.*` half are the matchers that stand in for a value instead of
592
991
  * being one. `expect(user).toEqual({ id: expect.any(String), name: "uf" })`
@@ -599,22 +998,4 @@ function expectValue(received: mixed): $FlowFixMe {
599
998
  * than a negated assertion around the whole object, and is the form a suite
600
999
  * being ported will already have.
601
1000
  */
602
- export const expect: $FlowFixMe = Object.assign(expectValue, {
603
- any: asymmetric.any,
604
- anything: asymmetric.anything,
605
- objectContaining: asymmetric.objectContaining,
606
- arrayContaining: asymmetric.arrayContaining,
607
- stringContaining: asymmetric.stringContaining,
608
- stringMatching: asymmetric.stringMatching,
609
- closeTo: asymmetric.closeTo,
610
- not: {
611
- objectContaining: (expected: interface {}) =>
612
- asymmetric.not(asymmetric.objectContaining(expected)),
613
- arrayContaining: (expected: $ReadOnlyArray<mixed>) =>
614
- asymmetric.not(asymmetric.arrayContaining(expected)),
615
- stringContaining: (substring: string) => asymmetric.not(asymmetric.stringContaining(substring)),
616
- stringMatching: (pattern: string | RegExp) =>
617
- asymmetric.not(asymmetric.stringMatching(pattern)),
618
- closeTo: (value: number, digits?: number) => asymmetric.not(asymmetric.closeTo(value, digits)),
619
- },
620
- });
1001
+ export const expect: Expect = expecting();