@gtkx/testing 2.0.0-beta.12 → 2.0.0-beta.13

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 (148) hide show
  1. package/dist/act.d.ts +7 -1
  2. package/dist/act.d.ts.map +1 -1
  3. package/dist/act.js +54 -4
  4. package/dist/act.js.map +1 -1
  5. package/dist/bound-queries.d.ts +1 -1
  6. package/dist/bound-queries.d.ts.map +1 -1
  7. package/dist/bound-queries.js.map +1 -1
  8. package/dist/cleanup-registry.d.ts.map +1 -1
  9. package/dist/cleanup-registry.js +4 -1
  10. package/dist/cleanup-registry.js.map +1 -1
  11. package/dist/fire-event.d.ts.map +1 -1
  12. package/dist/fire-event.js +11 -2
  13. package/dist/fire-event.js.map +1 -1
  14. package/dist/harness-window.d.ts +8 -2
  15. package/dist/harness-window.d.ts.map +1 -1
  16. package/dist/harness-window.js +28 -5
  17. package/dist/harness-window.js.map +1 -1
  18. package/dist/internal.d.ts +5 -0
  19. package/dist/internal.d.ts.map +1 -1
  20. package/dist/internal.js +5 -0
  21. package/dist/internal.js.map +1 -1
  22. package/dist/matchers.d.ts +4 -1
  23. package/dist/matchers.d.ts.map +1 -1
  24. package/dist/matchers.js +29 -9
  25. package/dist/matchers.js.map +1 -1
  26. package/dist/pretty-widget.d.ts +4 -2
  27. package/dist/pretty-widget.d.ts.map +1 -1
  28. package/dist/pretty-widget.js +7 -5
  29. package/dist/pretty-widget.js.map +1 -1
  30. package/dist/queries.d.ts +2 -1
  31. package/dist/queries.d.ts.map +1 -1
  32. package/dist/queries.js +19 -6
  33. package/dist/queries.js.map +1 -1
  34. package/dist/register-test-hooks.js +8 -0
  35. package/dist/register-test-hooks.js.map +1 -1
  36. package/dist/render.d.ts +14 -6
  37. package/dist/render.d.ts.map +1 -1
  38. package/dist/render.js +46 -31
  39. package/dist/render.js.map +1 -1
  40. package/dist/role-helpers.js.map +1 -1
  41. package/dist/types.d.ts +10 -2
  42. package/dist/types.d.ts.map +1 -1
  43. package/dist/types.js.map +1 -1
  44. package/dist/usage-error.d.ts +9 -0
  45. package/dist/usage-error.d.ts.map +1 -0
  46. package/dist/usage-error.js +13 -0
  47. package/dist/usage-error.js.map +1 -0
  48. package/dist/user-event/adjustment.d.ts.map +1 -1
  49. package/dist/user-event/adjustment.js +6 -5
  50. package/dist/user-event/adjustment.js.map +1 -1
  51. package/dist/user-event/click.d.ts +15 -7
  52. package/dist/user-event/click.d.ts.map +1 -1
  53. package/dist/user-event/click.js +165 -43
  54. package/dist/user-event/click.js.map +1 -1
  55. package/dist/user-event/controller.d.ts +10 -2
  56. package/dist/user-event/controller.d.ts.map +1 -1
  57. package/dist/user-event/controller.js +25 -3
  58. package/dist/user-event/controller.js.map +1 -1
  59. package/dist/user-event/dispatch.d.ts +1 -1
  60. package/dist/user-event/dispatch.d.ts.map +1 -1
  61. package/dist/user-event/dispatch.js +9 -6
  62. package/dist/user-event/dispatch.js.map +1 -1
  63. package/dist/user-event/editable-label-click.d.ts +5 -0
  64. package/dist/user-event/editable-label-click.d.ts.map +1 -0
  65. package/dist/user-event/editable-label-click.js +12 -0
  66. package/dist/user-event/editable-label-click.js.map +1 -0
  67. package/dist/user-event/event-wrapper.d.ts +11 -1
  68. package/dist/user-event/event-wrapper.d.ts.map +1 -1
  69. package/dist/user-event/event-wrapper.js +66 -12
  70. package/dist/user-event/event-wrapper.js.map +1 -1
  71. package/dist/user-event/gesture.d.ts.map +1 -1
  72. package/dist/user-event/gesture.js +67 -27
  73. package/dist/user-event/gesture.js.map +1 -1
  74. package/dist/user-event/index.d.ts +55 -18
  75. package/dist/user-event/index.d.ts.map +1 -1
  76. package/dist/user-event/index.js +42 -8
  77. package/dist/user-event/index.js.map +1 -1
  78. package/dist/user-event/keyboard.d.ts +27 -2
  79. package/dist/user-event/keyboard.d.ts.map +1 -1
  80. package/dist/user-event/keyboard.js +251 -30
  81. package/dist/user-event/keyboard.js.map +1 -1
  82. package/dist/user-event/list-row-click.d.ts +2 -1
  83. package/dist/user-event/list-row-click.d.ts.map +1 -1
  84. package/dist/user-event/list-row-click.js +10 -6
  85. package/dist/user-event/list-row-click.js.map +1 -1
  86. package/dist/user-event/native-click.d.ts +2 -1
  87. package/dist/user-event/native-click.d.ts.map +1 -1
  88. package/dist/user-event/native-click.js +16 -2
  89. package/dist/user-event/native-click.js.map +1 -1
  90. package/dist/user-event/pointer.d.ts +5 -3
  91. package/dist/user-event/pointer.d.ts.map +1 -1
  92. package/dist/user-event/pointer.js +72 -27
  93. package/dist/user-event/pointer.js.map +1 -1
  94. package/dist/user-event/selection.d.ts.map +1 -1
  95. package/dist/user-event/selection.js +46 -15
  96. package/dist/user-event/selection.js.map +1 -1
  97. package/dist/user-event/state.d.ts +2 -1
  98. package/dist/user-event/state.d.ts.map +1 -1
  99. package/dist/user-event/state.js +1 -1
  100. package/dist/user-event/state.js.map +1 -1
  101. package/dist/user-event/tab-view-click.d.ts +8 -0
  102. package/dist/user-event/tab-view-click.d.ts.map +1 -0
  103. package/dist/user-event/tab-view-click.js +37 -0
  104. package/dist/user-event/tab-view-click.js.map +1 -0
  105. package/dist/user-event/text.d.ts +3 -2
  106. package/dist/user-event/text.d.ts.map +1 -1
  107. package/dist/user-event/text.js +34 -14
  108. package/dist/user-event/text.js.map +1 -1
  109. package/dist/widget-accessible-properties.d.ts +13 -3
  110. package/dist/widget-accessible-properties.d.ts.map +1 -1
  111. package/dist/widget-accessible-properties.js +56 -17
  112. package/dist/widget-accessible-properties.js.map +1 -1
  113. package/dist/widget-target.d.ts.map +1 -1
  114. package/dist/widget-target.js +2 -1
  115. package/dist/widget-target.js.map +1 -1
  116. package/package.json +13 -8
  117. package/src/act.ts +70 -6
  118. package/src/bound-queries.ts +1 -1
  119. package/src/cleanup-registry.ts +5 -1
  120. package/src/fire-event.ts +17 -2
  121. package/src/harness-window.ts +37 -6
  122. package/src/internal.ts +5 -0
  123. package/src/matchers.ts +43 -9
  124. package/src/pretty-widget.ts +8 -5
  125. package/src/queries.ts +43 -10
  126. package/src/register-test-hooks.ts +11 -0
  127. package/src/render.tsx +56 -35
  128. package/src/role-helpers.ts +1 -1
  129. package/src/types.ts +11 -2
  130. package/src/usage-error.ts +16 -0
  131. package/src/user-event/adjustment.ts +11 -6
  132. package/src/user-event/click.ts +227 -47
  133. package/src/user-event/controller.ts +48 -3
  134. package/src/user-event/dispatch.ts +17 -7
  135. package/src/user-event/editable-label-click.ts +17 -0
  136. package/src/user-event/event-wrapper.ts +105 -14
  137. package/src/user-event/gesture.ts +101 -31
  138. package/src/user-event/index.ts +104 -36
  139. package/src/user-event/keyboard.ts +358 -35
  140. package/src/user-event/list-row-click.ts +12 -6
  141. package/src/user-event/native-click.ts +22 -3
  142. package/src/user-event/pointer.ts +101 -35
  143. package/src/user-event/selection.ts +71 -15
  144. package/src/user-event/state.ts +4 -2
  145. package/src/user-event/tab-view-click.ts +59 -0
  146. package/src/user-event/text.ts +39 -12
  147. package/src/widget-accessible-properties.ts +79 -18
  148. package/src/widget-target.ts +2 -1
package/src/matchers.ts CHANGED
@@ -22,6 +22,7 @@ import { formatRole } from "./role-helpers.js";
22
22
  import { type Container, descendants } from "./traversal.js";
23
23
  import {
24
24
  type CheckedState,
25
+ findHiddenCause,
25
26
  getWidgetAccessibleName,
26
27
  getWidgetCheckedState,
27
28
  getWidgetDescribedByText,
@@ -37,7 +38,6 @@ import {
37
38
  hasDisplayValue,
38
39
  isWidgetDisabled,
39
40
  isWidgetValueMatch,
40
- isWidgetVisible,
41
41
  } from "./widget-accessible-properties.js";
42
42
  import { getTypeTag } from "./widget-getters.js";
43
43
  import { isWindowActivated } from "./window-state.js";
@@ -167,7 +167,10 @@ type MatcherImplementations = {
167
167
  toBeDisabled: StateMatcher;
168
168
  /** Asserts the widget and all of its ancestors are sensitive. */
169
169
  toBeEnabled: StateMatcher;
170
- /** Asserts the widget and its ancestors are all visible, and that none of them is fully transparent. */
170
+ /**
171
+ * Asserts the widget and its ancestors are all visible and shown by their containers, as a collapsed
172
+ * revealer or an inactive stack page does not show its child, and that none of them is fully transparent.
173
+ */
171
174
  toBeVisible: StateMatcher;
172
175
  /** Asserts the widget's root is a window that is still in the toplevel list. */
173
176
  toBeRooted: StateMatcher;
@@ -260,7 +263,12 @@ const toHaveAccessibleErrorMessage: TextMatcher = textMatcher(
260
263
  );
261
264
 
262
265
  const toHaveSelection: TextMatcher = textMatcher("toHaveSelection", getWidgetSelection, "exact");
263
- const toBePressed: StateMatcher = booleanStateMatcher("toBePressed", "pressed", getWidgetPressedState);
266
+ const toBePressed: StateMatcher = booleanStateMatcher(
267
+ "toBePressed",
268
+ "pressed",
269
+ getWidgetPressedState,
270
+ checkedInsteadHint,
271
+ );
264
272
  const toBeRequired: StateMatcher = booleanStateMatcher("toBeRequired", "required", getWidgetRequiredState);
265
273
 
266
274
  const toContainAnyByRole: ContainmentMatcher<RoleQueryArgs> = containmentMatcher(
@@ -656,24 +664,33 @@ function toHaveTextContent(received: unknown, expected?: TextExpectation, option
656
664
  return textMatcher("toHaveTextContent", read, "substring")(received, expected);
657
665
  }
658
666
 
659
- function notApplicable(matcherName: string, stateName: string, widget: Gtk.Widget): Error {
667
+ function notApplicable(matcherName: string, stateName: string, widget: Gtk.Widget, hint = ""): Error {
660
668
  return new Error(
661
669
  `${matcherName}: widget does not expose a ${stateName} ` +
662
- `(role ${Gtk.AccessibleRole[widget.getAccessibleRole()]})\n${describeWidget(widget)}`,
670
+ `(role ${Gtk.AccessibleRole[widget.getAccessibleRole()]})${hint}\n${describeWidget(widget)}`,
663
671
  );
664
672
  }
665
673
 
674
+ function pressedInsteadHint(widget: Gtk.Widget): string {
675
+ return getWidgetPressedState(widget) === null ? "" : "; it exposes a pressed state instead; use toBePressed";
676
+ }
677
+
678
+ function checkedInsteadHint(widget: Gtk.Widget): string {
679
+ return getWidgetCheckedState(widget) === null ? "" : "; it exposes a checked state instead; use toBeChecked";
680
+ }
681
+
666
682
  function booleanStateMatcher(
667
683
  matcherName: string,
668
684
  stateName: string,
669
685
  read: (widget: Gtk.Widget) => boolean | null,
686
+ hint: (widget: Gtk.Widget) => string = () => "",
670
687
  ): StateMatcher {
671
688
  return (received: unknown): MatcherResult => {
672
689
  const widget = asWidget(received, matcherName);
673
690
  const state = read(widget);
674
691
 
675
692
  if (state === null) {
676
- throw notApplicable(matcherName, `${stateName} state`, widget);
693
+ throw notApplicable(matcherName, `${stateName} state`, widget, hint(widget));
677
694
  }
678
695
 
679
696
  return stateResult(widget, stateName, state);
@@ -771,7 +788,7 @@ function toBePartiallyPressed(received: unknown): MatcherResult {
771
788
  const state = readAccessibleState(widget, Gtk.AccessibleState.PRESSED);
772
789
 
773
790
  if (state === null) {
774
- throw notApplicable("toBePartiallyPressed", "pressed state", widget);
791
+ throw notApplicable("toBePartiallyPressed", "pressed state", widget, checkedInsteadHint(widget));
775
792
  }
776
793
 
777
794
  return stateResult(widget, "partially pressed", state === MIXED_TRISTATE);
@@ -795,7 +812,7 @@ function readCheckedState(widget: Gtk.Widget, matcherName: string): CheckedState
795
812
  const state = getWidgetCheckedState(widget);
796
813
 
797
814
  if (state === null) {
798
- throw notApplicable(matcherName, "checked state", widget);
815
+ throw notApplicable(matcherName, "checked state", widget, pressedInsteadHint(widget));
799
816
  }
800
817
 
801
818
  return state;
@@ -861,10 +878,27 @@ function toBeEnabled(received: unknown): MatcherResult {
861
878
  return stateResult(widget, "enabled", !isWidgetDisabled(widget));
862
879
  }
863
880
 
881
+ const HIDDEN_REASONS = {
882
+ hidden: "is hidden",
883
+ unshown: "is not shown by its parent",
884
+ transparent: "has opacity 0",
885
+ } as const;
886
+
864
887
  function toBeVisible(received: unknown): MatcherResult {
865
888
  const widget = asWidget(received, "toBeVisible");
889
+ const hidden = findHiddenCause(widget);
890
+
891
+ if (!hidden) {
892
+ return stateResult(widget, "visible", true);
893
+ }
894
+
895
+ const subject = hidden.widget === widget ? "it" : `its ancestor ${describeWidget(hidden.widget)}`;
896
+ const reason = HIDDEN_REASONS[hidden.cause];
866
897
 
867
- return stateResult(widget, "visible", isWidgetVisible(widget));
898
+ return {
899
+ pass: false,
900
+ message: () => `expected widget to be visible, but ${subject} ${reason}\n${describeWidget(widget)}`,
901
+ };
868
902
  }
869
903
 
870
904
  function toBeRooted(received: unknown): MatcherResult {
@@ -195,15 +195,15 @@ const formatWidget = (widget: Gtk.Widget, indentation: string, depth: number, ct
195
195
  const { config } = ctx;
196
196
  const tag = getTypeTag(widget);
197
197
  const attrs = formatAttrs(buildAttrs(widget, ctx.getId), config.colors);
198
- const openTag = `${paint(config.colors.tag, "<" + tag)}${attrs}${paint(config.colors.tag, ">")}`;
199
- const closeTag = paint(config.colors.tag, `</${tag}>`);
200
198
  const text = printableText(widget);
201
- const openLine = `${indentation}${openTag}${config.spacingOuter}`;
202
199
 
203
200
  if (!text && !widget.getFirstChild()) {
204
- return openLine;
201
+ return `${indentation}${paint(config.colors.tag, "<" + tag)}${attrs}${paint(config.colors.tag, " />")}${config.spacingOuter}`;
205
202
  }
206
203
 
204
+ const openTag = `${paint(config.colors.tag, "<" + tag)}${attrs}${paint(config.colors.tag, ">")}`;
205
+ const closeTag = paint(config.colors.tag, `</${tag}>`);
206
+ const openLine = `${indentation}${openTag}${config.spacingOuter}`;
207
207
  const textLine = text ? `${indentation}${config.indent}${text}${config.spacingOuter}` : "";
208
208
  const body = isPasswordWidget(widget) ? "" : formatBody(widget, indentation, depth, ctx);
209
209
 
@@ -216,6 +216,9 @@ const createWidgetPlugin = (options: PrettyWidgetOptions): NewPlugin => ({
216
216
  formatWidget(widget, indentation, 0, { getId: options.getId, config, maxDepth: options.maxDepth }),
217
217
  });
218
218
 
219
+ /** Prints widgets in snapshots as their widget tree, in the format of {@link prettyWidget}. */
220
+ const widgetSnapshotSerializer: NewPlugin = createWidgetPlugin({});
221
+
219
222
  const resolveMaxLength = (options: PrettyWidgetOptions): number => {
220
223
  const envLimit = process.env.DEBUG_PRINT_LIMIT ? Number(process.env.DEBUG_PRINT_LIMIT) : DEFAULT_MAX_LENGTH;
221
224
 
@@ -275,4 +278,4 @@ const logWidget = (container: Container | Container[], options?: PrettyWidgetOpt
275
278
  }
276
279
  };
277
280
 
278
- export { logWidget, prettyWidget, type PrettyWidgetOptions };
281
+ export { logWidget, prettyWidget, widgetSnapshotSerializer, type PrettyWidgetOptions };
package/src/queries.ts CHANGED
@@ -1,5 +1,14 @@
1
+ import * as Adw from "@gtkx/gi/adw";
1
2
  import * as Gtk from "@gtkx/gi/gtk";
2
- import type { ByRoleOptions, ByRoleValue, Matcher, MatcherOptions, NormalizerFn, QueryFamilies } from "./types.js";
3
+ import type {
4
+ ByRoleOptions,
5
+ ByRoleValue,
6
+ Matcher,
7
+ MatcherOptions,
8
+ NormalizerFn,
9
+ QueryFamilies,
10
+ WaitForOptions,
11
+ } from "./types.js";
3
12
  import { buildQueries, type BuiltQueries, type QueryAllBy } from "./build-queries.js";
4
13
  import { multipleFoundError, notFoundError } from "./errors.js";
5
14
  import { getDefaultNormalizer } from "./normalize.js";
@@ -277,6 +286,16 @@ const hasMatchingAccessibleStates = (widget: Gtk.Widget, options: ByRoleOptions)
277
286
  hasMatchingDescriptionState(widget, options) &&
278
287
  hasMatchingValueState(widget, options);
279
288
 
289
+ const isDialogContentShown = (widget: Gtk.Widget): boolean => {
290
+ if (!(widget instanceof Adw.Dialog)) {
291
+ return true;
292
+ }
293
+
294
+ const child = widget.getChild();
295
+
296
+ return child === null || child.getMapped();
297
+ };
298
+
280
299
  const isMatchingWidgetType = <T extends Gtk.Accessible>(
281
300
  widget: Gtk.Widget,
282
301
  options?: MatcherOptions<T>,
@@ -290,10 +309,22 @@ const hasMatchingAccessibleOptions = (widget: Gtk.Widget, options?: ByRoleOption
290
309
  return hasMatchingAccessibleName(widget, options) && hasMatchingAccessibleStates(widget, options);
291
310
  };
292
311
 
293
- function nameQueryFamily<Args extends unknown[], Element extends Gtk.Accessible>(
312
+ function withWaitForOptions<Expected, Result>(
313
+ find: (container: Container, expected: Expected, options?: MatcherOptions<Gtk.Widget>) => Promise<Result>,
314
+ ) {
315
+ return (
316
+ container: Container,
317
+ expected: Expected,
318
+ options?: MatcherOptions<Gtk.Widget>,
319
+ waitForOptions?: WaitForOptions,
320
+ ): Promise<Result> =>
321
+ find(container, expected, waitForOptions === undefined ? options : { ...options, ...waitForOptions });
322
+ }
323
+
324
+ function nameQueryFamily<Expected, Element extends Gtk.Accessible>(
294
325
  suffix: string,
295
- queryAllBy: QueryAllBy<Args, Element>,
296
- built: BuiltQueries<Args, Element>,
326
+ queryAllBy: QueryAllBy<[expected: Expected, options?: MatcherOptions<Gtk.Widget>], Element>,
327
+ built: BuiltQueries<[expected: Expected, options?: MatcherOptions<Gtk.Widget>], Element>,
297
328
  ): Record<string, unknown> {
298
329
  const [queryBy, getAllBy, getBy, findAllBy, findBy] = built;
299
330
 
@@ -302,15 +333,16 @@ function nameQueryFamily<Args extends unknown[], Element extends Gtk.Accessible>
302
333
  [`queryAllBy${suffix}`]: queryAllBy,
303
334
  [`getBy${suffix}`]: getBy,
304
335
  [`getAllBy${suffix}`]: getAllBy,
305
- [`findBy${suffix}`]: findBy,
306
- [`findAllBy${suffix}`]: findAllBy,
336
+ [`findBy${suffix}`]: withWaitForOptions(findBy),
337
+ [`findAllBy${suffix}`]: withWaitForOptions(findAllBy),
307
338
  };
308
339
  }
309
340
 
310
341
  /**
311
342
  * Finds every widget under the container whose accessible role matches `role` and that satisfies the given options.
312
343
  * Widgets that are not mapped are never matched, and widgets excluded from the accessibility tree are
313
- * skipped unless `options.hidden` is set.
344
+ * skipped unless `options.hidden` is set. An Adwaita dialog matches once its content is shown, which
345
+ * libadwaita does a frame after the dialog opens.
314
346
  * @param container Widget subtree to search.
315
347
  * @param role Accessible role to match.
316
348
  * @param options Additional accessible name, state, and value constraints.
@@ -324,7 +356,7 @@ function queryAllByRole<T extends Gtk.Accessible = Gtk.Widget>(
324
356
  const isInaccessible = buildInaccessibilityCheck();
325
357
 
326
358
  const matches = findAll(container, (widget) => {
327
- if (widget.getAccessibleRole() !== role) {
359
+ if (widget.getAccessibleRole() !== role || !isDialogContentShown(widget)) {
328
360
  return false;
329
361
  }
330
362
 
@@ -361,9 +393,10 @@ const collectMnemonicMatch = (
361
393
  };
362
394
 
363
395
  const labellingText = (widget: Gtk.Widget): string | null => {
364
- const ownLabel = widget.getAccessibleRole() === Gtk.AccessibleRole.LABEL ? null : getWidgetOwnLabel(widget);
396
+ const ownLabel = getWidgetOwnLabel(widget);
397
+ const isOwnText = widget.getAccessibleRole() === Gtk.AccessibleRole.LABEL && ownLabel === namingLabelText(widget);
365
398
 
366
- return ownLabel ?? getWidgetExternalLabelText(widget);
399
+ return (isOwnText ? null : ownLabel) ?? getWidgetExternalLabelText(widget);
367
400
  };
368
401
 
369
402
  const collectLabelMatches = (
@@ -1,9 +1,11 @@
1
1
  import { quit } from "@gtkx/runtime";
2
2
  import { getIsReactActEnvironment, setIsReactActEnvironment } from "./act.js";
3
3
  import { registerMatchers } from "./matchers.js";
4
+ import { widgetSnapshotSerializer } from "./pretty-widget.js";
4
5
  import { cleanup } from "./render.js";
5
6
 
6
7
  type RunnerHook = "beforeAll" | "afterEach" | "afterAll";
8
+ type SnapshotExpect = { addSnapshotSerializer: (serializer: typeof widgetSnapshotSerializer) => void };
7
9
 
8
10
  const callRunnerHook = (name: RunnerHook, callback: () => unknown): void => {
9
11
  const hook: unknown = Reflect.get(globalThis, name);
@@ -26,11 +28,20 @@ const registerActEnvironment = (): void => {
26
28
  });
27
29
  };
28
30
 
31
+ const registerSnapshotSerializer = (): void => {
32
+ const expect: unknown = Reflect.get(globalThis, "expect");
33
+
34
+ if (expect && typeof (expect as SnapshotExpect).addSnapshotSerializer === "function") {
35
+ (expect as SnapshotExpect).addSnapshotSerializer(widgetSnapshotSerializer);
36
+ }
37
+ };
38
+
29
39
  const registerTestRuntimeHooks = (): void => {
30
40
  registerActEnvironment();
31
41
  callRunnerHook("afterEach", cleanup);
32
42
  callRunnerHook("afterAll", quit);
33
43
  registerMatchers();
44
+ registerSnapshotSerializer();
34
45
  };
35
46
 
36
47
  registerTestRuntimeHooks();
package/src/render.tsx CHANGED
@@ -1,7 +1,8 @@
1
- import type { CaughtErrorInfo, Root, RootElement } from "@gtkx/react";
1
+ import type { Root, RootElement } from "@gtkx/react";
2
+ import * as Gio from "@gtkx/gi/gio";
2
3
  import * as Gtk from "@gtkx/gi/gtk";
3
4
  import { createRoot } from "@gtkx/react";
4
- import { isRootElement, settleAccessible } from "@gtkx/react/internal";
5
+ import { isRootElement, ParentWindowContext, settleAccessible } from "@gtkx/react/internal";
5
6
  import { type ErrorInfo, type ReactNode, StrictMode } from "react";
6
7
  import type { RenderResult } from "./bound-queries.js";
7
8
  import type { QueryMap, RenderOptions, ScreenshotOptions } from "./types.js";
@@ -9,13 +10,13 @@ import { runInAct, runWithActEnvironment } from "./act.js";
9
10
  import { addToCleanupQueue, runCleanup, runCleanupCallbacks } from "./cleanup-registry.js";
10
11
  import { getConfig } from "./config.js";
11
12
  import { scheduleWhenWindowReady } from "./frame-sync.js";
12
- import { createHarnessWindow, presentHarnessWindow } from "./harness-window.js";
13
+ import { createHarnessWindow, presentHarnessTransients, presentHarnessWindow } from "./harness-window.js";
13
14
  import { logWidget, type PrettyWidgetOptions } from "./pretty-widget.js";
14
15
  import { logRoles } from "./role-helpers.js";
15
16
  import { clearScreen, setScreen } from "./screen.js";
16
17
  import { captureScreen } from "./screenshot.js";
17
18
  import { type Container, roots, TOPLEVELS } from "./traversal.js";
18
- import { resetClipboard } from "./user-event/index.js";
19
+ import { resetClipboard, resetUserEventState } from "./user-event/index.js";
19
20
  import { requireWidget } from "./widget-target.js";
20
21
  import { findPresentedWindowFailure, findRenderedWindowFailure, mappedToplevels } from "./window-state.js";
21
22
  import { within } from "./within.js";
@@ -24,6 +25,7 @@ type ActiveRender = {
24
25
  root: Root;
25
26
  window: Gtk.Window | null;
26
27
  errors: RenderErrorState;
28
+ application: Gio.Application | null;
27
29
  };
28
30
 
29
31
  type ResolvedContainer = {
@@ -90,6 +92,7 @@ const disposeActiveRender = async (active: ActiveRender): Promise<void> => {
90
92
  await flushRender(active, active.root.unmount);
91
93
  } finally {
92
94
  active.window?.destroy();
95
+ active.application?.quit();
93
96
  }
94
97
  };
95
98
 
@@ -171,28 +174,22 @@ const settleRender = async (
171
174
  await settleWindow(settleTarget(resolved, container), findFailure, action);
172
175
  };
173
176
 
174
- const renderErrorHandlers = <Q extends QueryMap>(errors: RenderErrorState, options: RenderOptions<Q> | undefined) => {
175
- const handleError = (error: unknown): void => {
177
+ const renderErrorHandlers = <Q extends QueryMap>(errors: RenderErrorState, options: RenderOptions<Q> | undefined) => ({
178
+ onUncaughtError: (error: unknown): void => {
176
179
  errors.lastError = error instanceof Error ? error : new Error(String(error));
177
- };
178
-
179
- return {
180
- onUncaughtError: handleError,
181
- onCaughtError: (error: unknown, errorInfo: CaughtErrorInfo): void => {
182
- handleError(error);
183
- options?.onCaughtError?.(error, errorInfo);
184
- },
185
- onRecoverableError: (error: unknown, errorInfo: ErrorInfo): void => {
186
- options?.onRecoverableError?.(error, errorInfo);
187
- },
188
- };
189
- };
190
-
191
- const applyEnableAnimations = (areAnimationsEnabled: boolean): void => {
180
+ },
181
+ onCaughtError: options?.onCaughtError,
182
+ onRecoverableError: (error: unknown, errorInfo: ErrorInfo): void => {
183
+ options?.onRecoverableError?.(error, errorInfo);
184
+ },
185
+ });
186
+
187
+ const applyDisplaySettings = (areAnimationsEnabled: boolean): void => {
192
188
  const settings = Gtk.Settings.getDefault();
193
189
 
194
190
  if (settings) {
195
191
  settings.gtkEnableAnimations = areAnimationsEnabled;
192
+ settings.gtkCursorBlink = false;
196
193
  }
197
194
  };
198
195
 
@@ -200,27 +197,34 @@ const applyEnableAnimations = (areAnimationsEnabled: boolean): void => {
200
197
  * Renders React into native widgets and returns queries, debug helpers, and lifecycle controls.
201
198
  *
202
199
  * @remarks
203
- * Without a container, creates and presents a harness window. Its initially focused editable
204
- * keeps its text unselected, with the caret at the end.
200
+ * Without a container, creates and presents a harness window, which the tree sees as its parent
201
+ * window. Windows the tree opens over it, such as an Adwaita dialog rendered on its own, are shown
202
+ * again after it, so the topmost one is active as in a running application. Initially focused
203
+ * editables keep their text unselected, with the caret at the end. Carets do not blink, so a focused
204
+ * editable does not keep the display redrawing and GLib idle callbacks still run.
205
205
  *
206
206
  * Waits for layout and activation before resolving, so focus and other platform state can be
207
- * read immediately. A new harness waits for its own activation; a caller-owned or rendered
207
+ * read immediately. A new harness waits for its topmost window's activation; a caller-owned or rendered
208
208
  * window waits for application activation, since only presentation can claim it. A container
209
209
  * that is not shown requires no activation wait.
210
210
  *
211
211
  * Widgets outside all toplevels or inside a hidden window cannot receive pointer or keyboard
212
212
  * input. `userEvent` rejects after `actionabilityTimeout`; use `fireEvent` to drive them directly.
213
213
  *
214
+ * Errors an error boundary catches go to `onCaughtError` and do not fail the test. An error no boundary
215
+ * catches rejects this render, or the next rerender, unmount or cleanup, with that error.
216
+ *
214
217
  * @param element React element to render.
215
218
  * @param options Container, wrapper, custom queries, and render settings.
216
219
  * @returns Bound queries, debug helpers, and rerender/unmount controls.
217
- * @throws If a shown window is not laid out and activated within `windowActivationTimeout`.
220
+ * @throws If a shown window is not laid out and activated within `windowActivationTimeout`, or the tree
221
+ * throws an error no boundary catches.
218
222
  */
219
223
  const render = async <Q extends QueryMap = Record<never, never>>(
220
224
  element: ReactNode,
221
225
  options?: RenderOptions<Q>,
222
226
  ): Promise<RenderResult<Q>> => {
223
- applyEnableAnimations(options?.areAnimationsEnabled === true);
227
+ applyDisplaySettings(options?.areAnimationsEnabled === true);
224
228
  const baseElement: Container = options?.baseElement ?? TOPLEVELS;
225
229
  const Wrapper = options?.wrapper;
226
230
  const resolved = resolveContainer(options?.container);
@@ -228,23 +232,39 @@ const render = async <Q extends QueryMap = Record<never, never>>(
228
232
  const errors: RenderErrorState = { lastError: null };
229
233
  const root = createRoot(resolved.containerInfo, renderErrorHandlers(errors, options));
230
234
 
231
- const active: ActiveRender = { root, window: resolved.window, errors };
235
+ const active: ActiveRender = { root, window: resolved.window, errors, application: null };
232
236
  activeRenders.add(active);
233
237
  addToCleanupQueue(disposeAllActiveRenders);
234
238
  addToCleanupQueue(clearScreen);
235
239
  addToCleanupQueue(resetClipboard);
240
+ addToCleanupQueue(resetUserEventState);
236
241
 
237
242
  const wrap = (node: ReactNode): ReactNode => {
238
243
  const wrapped = Wrapper ? <Wrapper>{node}</Wrapper> : node;
239
-
240
- return options?.isReactStrictMode ? <StrictMode>{wrapped}</StrictMode> : wrapped;
244
+ const hosted =
245
+ resolved.window === null ? (
246
+ wrapped
247
+ ) : (
248
+ <ParentWindowContext.Provider value={resolved.window}>{wrapped}</ParentWindowContext.Provider>
249
+ );
250
+
251
+ return options?.isReactStrictMode ? <StrictMode>{hosted}</StrictMode> : hosted;
241
252
  };
242
253
 
243
- await flushRender(active, () => {
244
- root.render(wrap(element));
245
- });
246
- presentHarnessWindow(resolved.window);
254
+ const previousApplication = Gio.Application.getDefault();
255
+
256
+ try {
257
+ await flushRender(active, () => {
258
+ root.render(wrap(element));
259
+ });
260
+ } finally {
261
+ const application = Gio.Application.getDefault();
262
+ active.application = application === previousApplication ? null : application;
263
+ }
264
+
265
+ const transients = presentHarnessWindow(resolved.window);
247
266
  await settleRender(resolved, options?.container, "render");
267
+ await settleWindow(realizedWindow(presentHarnessTransients(transients)), findPresentedWindowFailure, "render");
248
268
  const container = resolveResultContainer(resolved, options?.container, baseElement);
249
269
 
250
270
  const result: RenderResult<Q> = {
@@ -275,8 +295,9 @@ const render = async <Q extends QueryMap = Record<never, never>>(
275
295
  };
276
296
 
277
297
  /**
278
- * Unmounts every active render and runs all registered cleanup callbacks,
279
- * resetting the screen and clipboard. Called automatically after each test.
298
+ * Unmounts every active render, quits the applications those renders started, and runs all
299
+ * registered cleanup callbacks, resetting the screen, the clipboard and the input the default `userEvent` still holds.
300
+ * Called automatically after each test.
280
301
  */
281
302
  const cleanup = async (): Promise<void> => {
282
303
  await runCleanup();
@@ -7,7 +7,7 @@ import { requireWidget } from "./widget-target.js";
7
7
 
8
8
  const ROLE_NAMES_BY_VALUE = enumNamesByValue(Gtk.AccessibleRole);
9
9
 
10
- function enumNamesByValue(enumObject: Record<string, string | number>): Map<number, string> {
10
+ function enumNamesByValue(enumObject: Readonly<Record<string, unknown>>): Map<number, string> {
11
11
  return new Map<number, string>(
12
12
  Object.entries(enumObject)
13
13
  .filter((entry): entry is [string, number] => typeof entry[1] === "number")
package/src/types.ts CHANGED
@@ -141,13 +141,19 @@ type QueryArgs<Kind extends QueryKind, T extends Gtk.Accessible> = Kind extends
141
141
  ? [value: Matcher, options?: MatcherOptions<T>]
142
142
  : [text: Matcher, options?: MatcherOptions<T>];
143
143
 
144
+ /**
145
+ * The arguments a variant takes after the family's own. As in Testing Library, `findBy` and `findAllBy` take
146
+ * their wait options third; options given with the matcher options also apply, and the third argument wins.
147
+ */
148
+ type VariantArgs<Variant> = Variant extends "findBy" | "findAllBy" ? [waitForOptions?: WaitForOptions] : [];
149
+
144
150
  /**
145
151
  * One family's query variants, each named for its variant followed by `Suffix` and taking `Head`
146
152
  * ahead of the family's own arguments.
147
153
  */
148
154
  type QueryFamily<Suffix extends string, Kind extends QueryKind, Head extends unknown[]> = {
149
155
  [K in keyof QueryFamilyReturns<Gtk.Widget> as `${K & string}${Suffix}`]: <T extends Gtk.Accessible = Gtk.Widget>(
150
- ...args: [...Head, ...QueryArgs<Kind, T>]
156
+ ...args: [...Head, ...QueryArgs<Kind, T>, ...VariantArgs<K>]
151
157
  ) => QueryFamilyReturns<T>[K];
152
158
  };
153
159
 
@@ -182,7 +188,10 @@ type RenderOptions<Q extends QueryMap = Record<never, never>> = {
182
188
  isReactStrictMode?: boolean | undefined;
183
189
  /** Enable widget animations during the test. */
184
190
  areAnimationsEnabled?: boolean | undefined;
185
- /** Called for errors caught by React error boundaries. */
191
+ /**
192
+ * Called for errors caught by React error boundaries, which never fail the test. They are logged when
193
+ * this is omitted.
194
+ */
186
195
  onCaughtError?: ((error: unknown, errorInfo: CaughtErrorInfo) => void) | undefined;
187
196
  /** Called for errors React recovered from automatically. */
188
197
  onRecoverableError?: ((error: unknown, errorInfo: ErrorInfo) => void) | undefined;
@@ -0,0 +1,16 @@
1
+ const usageErrors: WeakSet<Error> = new WeakSet();
2
+
3
+ /** Marks an error @gtkx/testing raises because it was called on a target or with input it cannot use. */
4
+ const usageError = <T extends Error>(error: T): T => {
5
+ usageErrors.add(error);
6
+
7
+ return error;
8
+ };
9
+
10
+ /**
11
+ * Whether @gtkx/testing raised this error because it was misused, such as typing into a widget that is not editable,
12
+ * rather than because the code under test threw it while handling the interaction.
13
+ */
14
+ const isUsageError = (reason: unknown): boolean => reason instanceof Error && usageErrors.has(reason);
15
+
16
+ export { isUsageError, usageError };
@@ -1,7 +1,8 @@
1
1
  import * as Gtk from "@gtkx/gi/gtk";
2
2
  import { scheduleNextFrame } from "../frame-sync.js";
3
3
  import { getTypeTag } from "../widget-getters.js";
4
- import { wrapEvent } from "./event-wrapper.js";
4
+ import { wrapPointerEvent } from "./event-wrapper.js";
5
+ import { usageError } from "../usage-error.js";
5
6
 
6
7
  /** A scroll distance in pixels along each axis. */
7
8
  type ScrollDelta = {
@@ -18,9 +19,11 @@ type ScrollAdjustments = {
18
19
 
19
20
  /** Moves a range to a value. */
20
21
  const slide = (widget: Gtk.Widget, value: number): Promise<void> =>
21
- wrapEvent(widget, () => {
22
+ wrapPointerEvent(widget, () => {
22
23
  if (!(widget instanceof Gtk.Range)) {
23
- throw new TypeError(`userEvent.slide requires a Gtk.Range (e.g. Gtk.Scale), got ${getTypeTag(widget)}`);
24
+ throw usageError(
25
+ new TypeError(`userEvent.slide requires a Gtk.Range (e.g. Gtk.Scale), got ${getTypeTag(widget)}`),
26
+ );
24
27
  }
25
28
 
26
29
  widget.emit("change-value", Gtk.ScrollType.JUMP, value);
@@ -72,12 +75,14 @@ const applyScrollDelta = (adjustment: Gtk.Adjustment | null, delta: number): voi
72
75
 
73
76
  /** Scrolls the widget or its nearest scrollable ancestor. */
74
77
  const scroll = (widget: Gtk.Widget, delta: ScrollDelta): Promise<void> =>
75
- wrapEvent(widget, async () => {
78
+ wrapPointerEvent(widget, async () => {
76
79
  const adjustments = resolveScrollAdjustments(widget);
77
80
 
78
81
  if (!adjustments) {
79
- throw new Error(
80
- "userEvent.scroll: no Gtk.ScrolledWindow or Gtk.Scrollable found on the widget or its ancestors",
82
+ throw usageError(
83
+ new Error(
84
+ "userEvent.scroll: no Gtk.ScrolledWindow or Gtk.Scrollable found on the widget or its ancestors",
85
+ ),
81
86
  );
82
87
  }
83
88