@openrewrite/recipes-react 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/dist/i18n/translate-hard-coded-strings.d.ts +67 -0
  2. package/dist/i18n/translate-hard-coded-strings.d.ts.map +1 -0
  3. package/dist/i18n/translate-hard-coded-strings.js +439 -0
  4. package/dist/i18n/translate-hard-coded-strings.js.map +1 -0
  5. package/dist/index.d.ts +2 -0
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +10 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/search/find-enzyme-usage.d.ts +4 -0
  10. package/dist/search/find-enzyme-usage.d.ts.map +1 -1
  11. package/dist/search/find-enzyme-usage.js +64 -4
  12. package/dist/search/find-enzyme-usage.js.map +1 -1
  13. package/dist/search/find-hard-coded-strings.d.ts +110 -0
  14. package/dist/search/find-hard-coded-strings.d.ts.map +1 -0
  15. package/dist/search/find-hard-coded-strings.js +987 -0
  16. package/dist/search/find-hard-coded-strings.js.map +1 -0
  17. package/dist/search/find-missing-use-client-directive.d.ts +2 -0
  18. package/dist/search/find-missing-use-client-directive.d.ts.map +1 -1
  19. package/dist/search/find-missing-use-client-directive.js +1 -0
  20. package/dist/search/find-missing-use-client-directive.js.map +1 -1
  21. package/dist/testing/enzyme-portals.d.ts +3 -5
  22. package/dist/testing/enzyme-portals.d.ts.map +1 -1
  23. package/dist/testing/enzyme-portals.js +8 -39
  24. package/dist/testing/enzyme-portals.js.map +1 -1
  25. package/dist/testing/enzyme-render-blockers.d.ts +10 -0
  26. package/dist/testing/enzyme-render-blockers.d.ts.map +1 -0
  27. package/dist/testing/enzyme-render-blockers.js +119 -0
  28. package/dist/testing/enzyme-render-blockers.js.map +1 -0
  29. package/dist/testing/enzyme-shared-wrapper.d.ts +26 -0
  30. package/dist/testing/enzyme-shared-wrapper.d.ts.map +1 -0
  31. package/dist/testing/enzyme-shared-wrapper.js +213 -0
  32. package/dist/testing/enzyme-shared-wrapper.js.map +1 -0
  33. package/dist/testing/enzyme-to-react-testing-library.d.ts +9 -2
  34. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  35. package/dist/testing/enzyme-to-react-testing-library.js +355 -16
  36. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  37. package/dist/testing/enzyme-usage.d.ts +5 -1
  38. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  39. package/dist/testing/enzyme-usage.js +48 -6
  40. package/dist/testing/enzyme-usage.js.map +1 -1
  41. package/dist/testing/enzyme-wrapper-scope.d.ts +7 -1
  42. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  43. package/dist/testing/enzyme-wrapper-scope.js +24 -9
  44. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  45. package/dist/util/json-and-javascript.d.ts +4 -0
  46. package/dist/util/json-and-javascript.d.ts.map +1 -0
  47. package/dist/util/json-and-javascript.js +37 -0
  48. package/dist/util/json-and-javascript.js.map +1 -0
  49. package/dist/util/module-imports.d.ts +36 -0
  50. package/dist/util/module-imports.d.ts.map +1 -1
  51. package/dist/util/module-imports.js +216 -0
  52. package/dist/util/module-imports.js.map +1 -1
  53. package/dist/util/test-source.d.ts +2 -0
  54. package/dist/util/test-source.d.ts.map +1 -0
  55. package/dist/util/test-source.js +5 -0
  56. package/dist/util/test-source.js.map +1 -0
  57. package/dist/zustand/entry-store.d.ts +9 -0
  58. package/dist/zustand/entry-store.d.ts.map +1 -0
  59. package/dist/zustand/entry-store.js +136 -0
  60. package/dist/zustand/entry-store.js.map +1 -0
  61. package/dist/zustand/redux-stores.d.ts +15 -4
  62. package/dist/zustand/redux-stores.d.ts.map +1 -1
  63. package/dist/zustand/redux-stores.js +155 -10
  64. package/dist/zustand/redux-stores.js.map +1 -1
  65. package/dist/zustand/redux-to-zustand.d.ts +29 -5
  66. package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
  67. package/dist/zustand/redux-to-zustand.js +629 -42
  68. package/dist/zustand/redux-to-zustand.js.map +1 -1
  69. package/dist/zustand/zustand-plan.d.ts +31 -6
  70. package/dist/zustand/zustand-plan.d.ts.map +1 -1
  71. package/dist/zustand/zustand-plan.js +320 -31
  72. package/dist/zustand/zustand-plan.js.map +1 -1
  73. package/package.json +1 -1
  74. package/src/i18n/translate-hard-coded-strings.ts +442 -0
  75. package/src/index.ts +7 -0
  76. package/src/search/find-enzyme-usage.ts +59 -6
  77. package/src/search/find-hard-coded-strings.ts +1006 -0
  78. package/src/search/find-missing-use-client-directive.ts +1 -1
  79. package/src/testing/enzyme-portals.ts +4 -44
  80. package/src/testing/enzyme-render-blockers.ts +113 -0
  81. package/src/testing/enzyme-shared-wrapper.ts +224 -0
  82. package/src/testing/enzyme-to-react-testing-library.ts +354 -19
  83. package/src/testing/enzyme-usage.ts +62 -5
  84. package/src/testing/enzyme-wrapper-scope.ts +24 -6
  85. package/src/util/json-and-javascript.ts +26 -0
  86. package/src/util/module-imports.ts +223 -0
  87. package/src/util/test-source.ts +2 -0
  88. package/src/zustand/entry-store.ts +131 -0
  89. package/src/zustand/redux-stores.ts +171 -11
  90. package/src/zustand/redux-to-zustand.ts +689 -48
  91. package/src/zustand/zustand-plan.ts +350 -29
@@ -1,6 +1,6 @@
1
- import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, or, RecipeRef, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
1
+ import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, or, randomId, RecipeRef, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
2
2
  import {isPlainText} from "@openrewrite/rewrite/text";
3
- import {AddDependencyOptions, autoFormat, Autodetect, capture, PrettierStyle, deconflict, findNodeResolutionResult, isTypeScript, isVendoredOrBundled, JavaScriptVisitor, JS, maybeRemoveImport, moduleBindings, namesUsedIn, pattern, raw, rewrite, scopeOf, StyleKind, Template, template, usesMethod} from "@openrewrite/rewrite/javascript";
3
+ import {AddDependencyOptions, autoFormat, Autodetect, capture, PrettierStyle, deconflict, findNodeResolutionResult, isTypeScript, isVendoredOrBundled, JavaScriptVisitor, JS, maybeAddImport, maybeRemoveImport, moduleBindings, namesUsedIn, pattern, raw, rewrite, scopeOf, StyleKind, Template, template, usesMethod} from "@openrewrite/rewrite/javascript";
4
4
  import {Expression, J} from "@openrewrite/rewrite/java";
5
5
  import {create} from "mutative";
6
6
  import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
@@ -10,11 +10,13 @@ import {satisfies, valid, validRange} from "semver";
10
10
  import {FindEnzymeUsage} from "../search/find-enzyme-usage";
11
11
  import {JavaDependencyRecipe, treesOfType} from "../util/java-recipe-proxy";
12
12
  import {importBindings} from "../util/module-imports";
13
- import {ENZYME, ENZYME_USAGE_TABLE, enclosingScope, enzymeMethod, EnzymeUsageRow} from "./enzyme-usage";
13
+ import {ENZYME, ENZYME_USAGE_TABLE, enclosingScope, enzymeMethod, EnzymeUsageRow, FILE_BLOCKER, RENDER_BLOCKERS} from "./enzyme-usage";
14
+ import {blockedByFile, blockedByGate, blockedByUses, FileGate} from "./enzyme-render-blockers";
14
15
  import {HostComponents, hostComponentExports, hostComponentsDeclared, ImportedExport, importedNames, propsRenderHostElements, relativeImports, rendersHostElements} from "./enzyme-host-components";
15
16
  import {moduleFacts, Modules, rendersPortal, resolver} from "./enzyme-portals";
16
17
  import {evaluate, stringParts} from "./enzyme-constant-strings";
17
18
  import {hostOnlyNames, selectorNames, SelectorNames} from "./enzyme-selector-names";
19
+ import {expressionOf, SharedHook, SharedWrapper, sharedWrapper, withNewIds} from "./enzyme-shared-wrapper";
18
20
  import {analyzeWrapperScope, SIMULATED_EVENTS, idsWithin, innermostCall, mountedElement, passesRef, selectorLiteral, simpleChain, statementPosition, throwingPosition, variableCursor, withoutEnzymeTypes, withRenderOptionsOnElementLine, wrapperDeclaration, WrapperRead, WrapperUse} from "./enzyme-wrapper-scope";
19
21
 
20
22
  const RTL = "@testing-library/react";
@@ -77,6 +79,9 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
77
79
  */
78
80
  readonly landed = new Set<string>();
79
81
 
82
+ /** The package roots whose edit `AddDependency` declined, such as for a lockfile it could not regenerate. Mutated in place too. */
83
+ readonly declined = new Set<string>();
84
+
80
85
  private readonly manifests: Json.Document[] = [];
81
86
 
82
87
  /** The manifests the step admits, which reach the Java recipe only in `generate`, once the forecast is known. */
@@ -88,6 +93,7 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
88
93
 
89
94
  override initialValue(): number {
90
95
  this.landed.clear();
96
+ this.declined.clear();
91
97
  this.manifests.length = 0;
92
98
  this.held.length = 0;
93
99
  return super.initialValue();
@@ -122,7 +128,7 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
122
128
  const scopes = lockfileScopes(this.held);
123
129
  const forwarded = new Set(this.held.filter(manifest => {
124
130
  const scope = scopes.get(manifest.sourcePath) ?? packageRoot(manifest.sourcePath);
125
- return !converting || [...converting].some(source => source.startsWith(scope));
131
+ return (!converting || [...converting].some(source => source.startsWith(scope))) && !this.withholds(scope);
126
132
  }));
127
133
  const scanner = await this.java.scanner(acc);
128
134
  for (const manifest of forwarded) await scanner.visit(manifest, ctx);
@@ -133,10 +139,33 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
133
139
  const editor = await this.java.editorWithData(acc);
134
140
  for (const manifest of this.manifests) {
135
141
  const edited = await editor.visit<Json.Document>(manifest, ctx);
136
- if (edited && edited !== manifest && declares(edited, this.addition.packageName)) this.landed.add(manifest.sourcePath.slice(0, -"package.json".length));
142
+ const root = manifest.sourcePath.slice(0, -"package.json".length);
143
+ if (edited && edited !== manifest && declares(edited, this.addition.packageName)) this.landed.add(root);
144
+ else if (!declares(manifest, this.addition.packageName) && this.resolvesGate(manifest)) this.declined.add(root);
137
145
  }
138
146
  return generated;
139
147
  }
148
+
149
+ /** Whether the package resolves what `onlyIfResolving` asks, as `AddDependency` checks before it edits. */
150
+ private resolvesGate(manifest: Json.Document): boolean {
151
+ const resolved = findNodeResolutionResult(manifest)?.resolvedDependencies ?? [];
152
+ return (this.addition.onlyIfResolving ?? []).every(gate => {
153
+ const at = gate.lastIndexOf("@");
154
+ const name = gate.slice(0, at);
155
+ return resolved.some(dep => dep.name === name && valid(dep.version) !== null && satisfies(dep.version, gate.slice(at + 1)));
156
+ });
157
+ }
158
+
159
+ /** Whether to keep the manifests of a lockfile scope, such as `packages/ui/` or the root's `""`, from the Java recipe. */
160
+ protected withholds(_scope: string): boolean {
161
+ return false;
162
+ }
163
+ }
164
+
165
+ function dependencySteps(forecast: ConversionForecast) {
166
+ const rtl = new AddTestingLibraryReact(forecast);
167
+ const dom18 = new AddTestingLibraryDom18(forecast);
168
+ return {rtl, dom18, rtl18: new AddTestingLibraryReact18(forecast, dom18)};
140
169
  }
141
170
 
142
171
  /** Adds {@link RTL_ADDITION}. */
@@ -156,9 +185,15 @@ export class AddTestingLibraryReact18 extends EnzymeTestDependency {
156
185
  readonly displayName = "Add `@testing-library/react` 16 where Enzyme tests on React 18 are migrated";
157
186
  readonly description = "Adds `@testing-library/react` 16 as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 18.";
158
187
 
159
- constructor(forecast: ConversionForecast = {}) {
188
+ constructor(forecast: ConversionForecast = {}, private readonly peer?: AddTestingLibraryDom18) {
160
189
  super(RTL_18_ADDITION, forecast);
161
190
  }
191
+
192
+ // NOTE: RTL 16 needs its peer `@testing-library/dom`, whose step runs first. Where that step's edit was declined,
193
+ // as when a registry timeout fails its lockfile, this step adds nothing in the same lockfile either.
194
+ protected override withholds(scope: string): boolean {
195
+ return !!this.peer && [...this.peer.declined].some(root => root.startsWith(scope));
196
+ }
162
197
  }
163
198
 
164
199
  /** Adds {@link DOM_18_ADDITION}, the peer of {@link RTL_18_ADDITION}. */
@@ -378,6 +413,11 @@ export function reactMajor(packages: Packages, sourcePath: string, landed: Reado
378
413
  return compatibility(packages, sourcePath, landed).react;
379
414
  }
380
415
 
416
+ /** Why {@link reactMajor} is 0 for a source file, as far as its package's declarations say. */
417
+ export function incompatibility(packages: Packages, sourcePath: string, landed: ReadonlySet<string> = new Set()): FileGate | undefined {
418
+ return compatibility(packages, sourcePath, landed).why;
419
+ }
420
+
381
421
  /** The events `simulate` can dispatch as `fireEvent` in a source file, and whether its render must be attached to the document for them. */
382
422
  export interface SimulatedEvents {
383
423
  events: ReadonlySet<string>;
@@ -403,7 +443,7 @@ export function simulatesEvents(packages: Packages, sourcePath: string, landed:
403
443
  }
404
444
 
405
445
  /** The React major as {@link reactMajor} reads it, and the major of the RTL the tests run with. */
406
- function compatibility(packages: Packages, sourcePath: string, landed: ReadonlySet<string>): {react: number, rtl: number} {
446
+ function compatibility(packages: Packages, sourcePath: string, landed: ReadonlySet<string>): {react: number, rtl: number, why?: FileGate} {
407
447
  const roots = [...packages.keys()].filter(root => sourcePath.startsWith(root)).sort((a, b) => b.length - a.length);
408
448
  const declared = (name: "react" | "reactDom" | "rtl", from = roots) =>
409
449
  from.map(root => packages.get(root)![name]).find(version => version !== undefined);
@@ -424,7 +464,10 @@ function compatibility(packages: Packages, sourcePath: string, landed: ReadonlyS
424
464
  const rtlMajor = added ? ((enzymeReact as DeclaredVersion).major >= 18 ? 16 : 12) : typeof rtl === "object" && rtl.major >= 10 && rtl.major <= 16 ? rtl.major : 0;
425
465
  const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major &&
426
466
  rtlMajor > 0 && rtlSupports(rtlMajor, react.major);
427
- return {react: compatible ? react.major : 0, rtl: rtlMajor};
467
+ if (compatible) return {react: react.major, rtl: rtlMajor};
468
+ const why: FileGate = !supportedReact(react) || !supportedReact(reactDom) || react.major !== reactDom.major ? "react" :
469
+ rtl === undefined && !added ? "rtlMissing" : "rtl";
470
+ return {react: 0, rtl: rtlMajor, why};
428
471
  }
429
472
 
430
473
  /**
@@ -476,6 +519,31 @@ function declaredVersion(version: string | undefined): Declaration {
476
519
  return {major: Number(match[2]), minor: /^\d+$/.test(match[3] ?? "") ? Number(match[3]) : undefined};
477
520
  }
478
521
 
522
+ /** The statements with `statement` after the last of them that was before it. */
523
+ function inserted<T extends {element: J}>(statements: readonly T[], before: readonly string[], statement: T): T[] {
524
+ const at = statements.reduce((last, padded, i) => before.includes(padded.element.id) ? i + 1 : last, 0);
525
+ return [...statements.slice(0, at), statement, ...statements.slice(at)];
526
+ }
527
+
528
+ /** The statements with the prefixes they had before others were taken out of their block and put back. */
529
+ function withPrefixes<T extends {element: J}>(statements: readonly T[], prefixes: ReadonlyMap<string, J["prefix"]>): T[] {
530
+ return statements.map(padded => {
531
+ const prefix = prefixes.get(padded.element.id);
532
+ return prefix && prefix !== padded.element.prefix ? {...padded, element: {...padded.element, prefix}} : padded;
533
+ });
534
+ }
535
+
536
+ /** The block without the statements of `removed`, its first statement keeping the block's first prefix. */
537
+ function withoutStatements(block: J.Block, removed: ReadonlySet<string>): J.Block {
538
+ if (!block.statements.some(statement => removed.has(statement.element.id))) return block;
539
+ const kept = block.statements.filter(statement => !removed.has(statement.element.id));
540
+ const first = block.statements[0].element.prefix;
541
+ return create(block, draft => {
542
+ draft.statements = kept.map((statement, i) => i === 0 && kept[0] !== block.statements[0] ?
543
+ {...statement, element: {...statement.element, prefix: first}} : statement) as any;
544
+ });
545
+ }
546
+
479
547
  /**
480
548
  * Converts an Enzyme `mount` wrapper only when all of its uses can be converted together, so no
481
549
  * partially migrated wrapper can escape. Inline expressions such as
@@ -520,8 +588,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
520
588
  // PERF: the sources that import Enzyme, kept from the scan to the forecast in `generate`, as the dependency steps keep
521
589
  // their manifests. Not in the accumulator, which the host keeps until the cycle ends; cleared once the forecast is made.
522
590
  private readonly tests: JS.CompilationUnit[] = [];
523
- private readonly dependencySteps = ADDS_RTL ? {rtl: new AddTestingLibraryReact(this.forecast), rtl18: new AddTestingLibraryReact18(this.forecast),
524
- dom18: new AddTestingLibraryDom18(this.forecast)} : undefined;
591
+ private readonly dependencySteps = ADDS_RTL ? dependencySteps(this.forecast) : undefined;
525
592
 
526
593
  constructor(options?: {untaggedSelectorPositions?: boolean}) {
527
594
  super(options);
@@ -700,6 +767,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
700
767
  private cu?: JS.CompilationUnit;
701
768
  private readonly portals = new Set<string>();
702
769
  private readonly rows: EnzymeUsageRow[] = [];
770
+ // What kept each mount analyzed in this source on Enzyme
771
+ private readonly blockers = new Map<string, string>();
703
772
  private prettier = false;
704
773
  private printWidth = 80;
705
774
 
@@ -709,6 +778,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
709
778
  this.hoists.clear();
710
779
  this.hoistedMounts.clear();
711
780
  this.rows.length = 0;
781
+ this.blockers.clear();
782
+ if (!dry) RENDER_BLOCKERS.delete(cu.sourcePath);
712
783
  this.names = namesUsedIn(cu);
713
784
  const prettierStyle = findMarker<PrettierStyle>(cu, StyleKind.PrettierStyle);
714
785
  this.prettier = prettierStyle !== undefined && !prettierStyle.ignored && await formattedBy(cu, prettierStyle);
@@ -721,7 +792,12 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
721
792
  this.typescript = isTypeScript(cu);
722
793
  this.optionalChaining = parsesOptionalChaining(scanned.packages, cu.sourcePath, this.typescript);
723
794
  this.enabled = this.reactMajor > 0 && moduleBindings(this).moduleSystem === "esm";
724
- if (!this.enabled) return cu;
795
+ if (!this.enabled) {
796
+ // Every render of the file stays on Enzyme for the same reason
797
+ const why = this.reactMajor === 0 ? incompatibility(scanned.packages, cu.sourcePath, landed) : "commonjs";
798
+ if (!dry && why) RENDER_BLOCKERS.set(cu.sourcePath, new Map([[FILE_BLOCKER, blockedByFile(why)]]));
799
+ return cu;
800
+ }
725
801
  this.imports = relativeImports(cu, scanned.components);
726
802
  this.importedNames = importedNames(cu);
727
803
  this.declaredHost = hostComponentsDeclared(cu);
@@ -737,7 +813,10 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
737
813
  const visited = await super.visitJsCompilationUnit(visiting, ctx);
738
814
  if (dry) {
739
815
  if (this.rows.some(row => row.status === "CONVERTED")) dry.converted.add(cu.sourcePath);
740
- } else this.rows.forEach(row => usages.insertRow(ctx, row));
816
+ } else {
817
+ this.rows.forEach(row => usages.insertRow(ctx, row));
818
+ if (this.blockers.size > 0) RENDER_BLOCKERS.set(cu.sourcePath, new Map(this.blockers));
819
+ }
741
820
  if (!foreign || !visited) return visited;
742
821
  return visited === visiting ? cu : create(visited as JS.CompilationUnit, draft => {
743
822
  draft.markers.markers.push(prettierStyle as any);
@@ -745,6 +824,244 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
745
824
  }
746
825
 
747
826
  override async visitBlock(block: J.Block, ctx: ExecutionContext): Promise<J | undefined> {
827
+ const shared = block.statements.map(statement => sharedWrapper(this.cursor, statement.element))
828
+ .filter((wrapper): wrapper is SharedWrapper => wrapper !== undefined);
829
+ if (shared.length === 0) return this.convertBlock(block, ctx);
830
+ const saved = this.saveState();
831
+ const original = this.cursor;
832
+ const {candidate, mounts} = await this.mountedInEachTest(block, shared, ctx);
833
+ this.cursor = new Cursor(candidate, original.parent);
834
+ const converted = await this.convertBlock(candidate, ctx);
835
+ this.cursor = original;
836
+ // Each test's wrapper converts, or the shared wrapper and every test keep Enzyme
837
+ if (mounts.every(id => this.mounts.has(id) && !this.pending.has(id))) return this.renderedInHooks(converted as J.Block, block, shared, ctx);
838
+ this.restoreState(saved);
839
+ return this.convertBlock(block, ctx);
840
+ }
841
+
842
+ /**
843
+ * The converted block with the renders each test of a describe starts with put back in the `beforeEach` they came
844
+ * from, where they are all the same, and the shared wrapper declared again for them. RTL renders in a hook as
845
+ * well, which keeps the tests as they were written, and its cleanup unmounts each render after its test.
846
+ */
847
+ private async renderedInHooks(block: J.Block, original: J.Block, shared: SharedWrapper[], ctx: ExecutionContext): Promise<J.Block> {
848
+ const groups = shared.flatMap(wrapper => wrapper.hooks.map(hook => ({wrapper, hook})));
849
+ if (groups.length === 0) return block;
850
+ const wanted = new Set(groups.flatMap(({hook}) => hook.tests));
851
+ const bodies = new Map<string, J.Block>();
852
+ await new class extends JavaScriptVisitor<ExecutionContext> {
853
+ override async visitBlock(inner: J.Block, p: ExecutionContext): Promise<J | undefined> {
854
+ if (wanted.has(inner.id)) bodies.set(inner.id, inner);
855
+ return super.visitBlock(inner, p);
856
+ }
857
+ }().visit(block, ctx, this.cursor.parent);
858
+ // NOTE: Prettier may lay out one test's render apart from the others', and quote it in its own style
859
+ const printer = TreePrinters.printer(JS.Kind.CompilationUnit);
860
+ const normalized = async (node: J) => (await printer.print(node)).replace(/\s+/g, "").replace(/"/g, "'");
861
+ const folds = new Map<string, {name: string, hook: SharedHook, render: Expression}>();
862
+ for (const {wrapper, hook} of groups) {
863
+ const firsts = hook.tests.map(id => bodies.get(id)?.statements[0]?.element);
864
+ if (firsts.length === 0 || firsts.some(first => first?.kind !== J.Kind.VariableDeclarations)) continue;
865
+ const renders = (firsts as J.VariableDeclarations[]).map(first => first.variables[0].element.initializer?.element);
866
+ if (renders.some(render => !render)) continue;
867
+ const printed = await Promise.all(renders.map(render => normalized(render!)));
868
+ if (printed.some(text => text !== printed[0])) continue;
869
+ folds.set(hook.owner, {name: wrapper.name, hook, render: renders[0]!});
870
+ }
871
+ if (folds.size === 0) return block;
872
+ const folded = new Set([...folds.values()].flatMap(({hook}) => hook.tests));
873
+ const declarations = shared.filter(wrapper => wrapper.hooks.some(hook => folds.has(hook.owner)))
874
+ .map(wrapper => wrapper.declaration);
875
+ const outer = this;
876
+ const visited = await new class extends JavaScriptVisitor<ExecutionContext> {
877
+ override async visitBlock(inner: J.Block, p: ExecutionContext): Promise<J | undefined> {
878
+ let visited = await super.visitBlock(inner, p) as J.Block;
879
+ if (folded.has(visited.id)) {
880
+ const [first, second, ...rest] = visited.statements;
881
+ return create(visited, draft => {
882
+ draft.statements = (second ? [{...second, element: {...second.element, prefix: first.element.prefix}}, ...rest] : []) as any;
883
+ });
884
+ }
885
+ const fold = folds.get(visited.id);
886
+ if (fold) visited = await outer.withHook(visited, fold, p);
887
+ if (visited.id === block.id) visited = await outer.withDeclarations(visited, original, declarations, p);
888
+ return visited;
889
+ }
890
+ }().visit<J.Block>(block, ctx, this.cursor.parent);
891
+ return visited!;
892
+ }
893
+
894
+ /** The describe with its `beforeEach` assigning the shared wrapper the render its tests started with. */
895
+ private async withHook(describe: J.Block, {hook, render}: {name: string, hook: SharedHook, render: Expression}, ctx: ExecutionContext): Promise<J.Block> {
896
+ const kept = describe.statements.find(statement => statement.element.id === hook.hook.id);
897
+ const statement = (kept?.element ?? hook.hook) as J;
898
+ const arrow = (expressionOf(statement) as J.MethodInvocation).arguments.elements[0].element as JS.ArrowFunction;
899
+ const body = arrow.lambda.body as J.Block;
900
+ const originalBody = ((expressionOf(hook.hook) as J.MethodInvocation).arguments.elements[0].element as JS.ArrowFunction).lambda.body as J.Block;
901
+ const mounting = originalBody.statements.find(padded => padded.element.id === hook.mounting)!;
902
+ // The render was converted from a copy of the hook's mount, so it keeps the hook's layout
903
+ const assigned = await withoutEnzymeTypes(create(mounting.element, (draft: any) => {
904
+ const assignment = draft.kind === JS.Kind.ExpressionStatement ? draft.expression : draft;
905
+ assignment.assignment.element = {...render, prefix: assignment.assignment.element.prefix};
906
+ assignment.type = undefined;
907
+ }), ctx);
908
+ const statements = [...body.statements.filter(padded => padded.element.id !== hook.mounting), {...mounting, element: assigned}];
909
+ const withBody = create(statement, (draft: any) => {
910
+ const target = draft.kind === JS.Kind.ExpressionStatement ? draft.expression : draft;
911
+ target.arguments.elements[0].element.lambda.body.statements = statements;
912
+ });
913
+ const statements2 = kept ? describe.statements.map(padded => padded === kept ? {...padded, element: withBody} : padded) :
914
+ inserted(describe.statements, hook.before, {...describe.statements[0], element: withBody});
915
+ return create(describe, draft => {
916
+ draft.statements = withPrefixes(statements2, hook.prefixes) as any;
917
+ });
918
+ }
919
+
920
+ /** The block with the shared wrappers declared again where they were, without their Enzyme types. */
921
+ private async withDeclarations(block: J.Block, original: J.Block, declarations: J.VariableDeclarations[], ctx: ExecutionContext): Promise<J.Block> {
922
+ let statements = [...block.statements];
923
+ const ids = original.statements.map(padded => padded.element.id);
924
+ for (const declaration of declarations) {
925
+ const padded = original.statements.find(statement => statement.element.id === declaration.id)!;
926
+ statements = inserted(statements, ids.slice(0, ids.indexOf(declaration.id)), {...padded, element: await this.renderResultDeclaration(declaration, original)});
927
+ }
928
+ const prefixes = new Map(original.statements.map(padded => [padded.element.id, padded.element.prefix] as const));
929
+ return create(block, draft => {
930
+ draft.statements = withPrefixes(statements, prefixes) as any;
931
+ });
932
+ }
933
+
934
+ /** The shared wrapper's declaration, typed as RTL's `RenderResult` where it had a type, which an Enzyme type was. */
935
+ private async renderResultDeclaration(declaration: J.VariableDeclarations, block: J.Block): Promise<J.VariableDeclarations> {
936
+ if (!declaration.typeExpression) return declaration;
937
+ const local = maybeAddImport(this, {module: RTL, member: "RenderResult", typeOnly: true, onlyIfReferenced: false}) ?? "RenderResult";
938
+ const name = (declaration.variables[0].element.name as J.Identifier).simpleName;
939
+ const typed = await Template.builder().code(`let ${name}: ${local}`).build()
940
+ .apply(declaration, new Cursor(declaration, new Cursor(block, this.cursor.parent))) as J.VariableDeclarations | undefined;
941
+ if (!typed) throw new Error(`Cannot declare ${name}`);
942
+ return {...typed, prefix: declaration.prefix};
943
+ }
944
+
945
+ /**
946
+ * The block with each test declaring the shared wrapper it mounts, without the shared declaration, its
947
+ * cleanup in `afterEach`, or the tests clearing it. An unmount that `afterEach` does before other statements
948
+ * becomes RTL's `cleanup()`, which keeps the order, and one after them is dropped, as RTL unmounts after them too.
949
+ */
950
+ private async mountedInEachTest(block: J.Block, shared: SharedWrapper[], ctx: ExecutionContext): Promise<{candidate: J.Block, mounts: string[]}> {
951
+ const names = new Map<string, string>();
952
+ shared.forEach(wrapper => wrapper.assignments.forEach(id => names.set(id, wrapper.name)));
953
+ const cleanup = new Set(shared.flatMap(wrapper => [...wrapper.cleanup]));
954
+ const unmounts = new Set(shared.flatMap(wrapper => [...wrapper.unmounts]));
955
+ const clears = new Set(shared.flatMap(wrapper => [...wrapper.clears, ...wrapper.hookRemovals]));
956
+ const hookMounts = new Map(shared.flatMap(wrapper => [...wrapper.hookMounts].map(([body, mount]) => [body, {name: wrapper.name, mount}] as const)));
957
+ const whole = (afterEach: J) => {
958
+ const body = (expressionOf(afterEach) as J.MethodInvocation).arguments.elements[0].element as JS.ArrowFunction;
959
+ const statements = body.lambda.body.kind === J.Kind.Block ? (body.lambda.body as J.Block).statements.map(s => s.element) : [body.lambda.body];
960
+ return statements.every(statement => cleanup.has(statement.id));
961
+ };
962
+ const removed = new Set(shared.flatMap(wrapper => [wrapper.declaration.id, ...wrapper.afterEach && whole(wrapper.afterEach) ? [wrapper.afterEach.id] : []]));
963
+ const trimmed = withoutStatements(block, removed);
964
+ const mounts: string[] = [];
965
+ const outer = this;
966
+ const candidate = await new class extends JavaScriptVisitor<ExecutionContext> {
967
+ override async visitBlock(inner: J.Block, p: ExecutionContext): Promise<J | undefined> {
968
+ const visited = await this.mountedFirst(await super.visitBlock(inner, p) as J.Block);
969
+ const own = (statement: J.Block["statements"][number]) => names.has(expressionOf(statement.element).id) ||
970
+ cleanup.has(statement.element.id) || clears.has(statement.element.id);
971
+ if (!visited.statements.some(own)) return visited;
972
+ const others = visited.statements.map(statement => cleanup.has(statement.element.id));
973
+ const last = others.lastIndexOf(false);
974
+ let cleaned = false;
975
+ const dropped = new Set<string>();
976
+ const statements: J.Block["statements"][number][] = [];
977
+ for (const [i, statement] of visited.statements.entries()) {
978
+ const id = statement.element.id;
979
+ const cursor = new Cursor(statement.element, new Cursor(visited, this.cursor.parent));
980
+ if (clears.has(id) || cleanup.has(id) && (cleaned || i > last || !unmounts.has(id))) {
981
+ dropped.add(id);
982
+ statements.push(statement);
983
+ continue;
984
+ }
985
+ if (cleanup.has(id)) {
986
+ const local = maybeAddImport(outer, {module: RTL, member: "cleanup", onlyIfReferenced: false}) ?? "cleanup";
987
+ const replaced = await Template.builder().code(`${local}()`).build().apply(statement.element, cursor) as J | undefined;
988
+ if (!replaced) throw new Error("Cannot clean up the shared wrapper");
989
+ cleaned = true;
990
+ // An `if` ends without a semicolon, which the call takes where the block's other statements have one
991
+ const semicolon = (padded: J.Block["statements"][number]) => padded.markers.markers.some(marker => marker.kind === J.Markers.Semicolon);
992
+ const markers = semicolon(statement) || !visited.statements.some(semicolon) ? statement.markers :
993
+ {...statement.markers, markers: [...statement.markers.markers, {kind: J.Markers.Semicolon, id: randomId()}]};
994
+ statements.push({...statement, markers, element: {...replaced, prefix: statement.element.prefix}});
995
+ continue;
996
+ }
997
+ const assignment = expressionOf(statement.element) as J.Assignment;
998
+ const name = names.get(assignment.id);
999
+ if (name === undefined) {
1000
+ statements.push(statement);
1001
+ continue;
1002
+ }
1003
+ const declare = Template.builder().code(`const ${name} = `).param(assignment.assignment.element).build();
1004
+ const declared = await declare.apply(statement.element, cursor) as J.VariableDeclarations | undefined;
1005
+ if (!declared) throw new Error(`Cannot declare ${name}`);
1006
+ mounts.push(declared.variables[0].element.initializer!.element.id);
1007
+ statements.push({...statement, element: {...declared, prefix: statement.element.prefix}});
1008
+ }
1009
+ return withoutStatements(create(visited, draft => {
1010
+ draft.statements = statements as any;
1011
+ }), dropped);
1012
+ }
1013
+
1014
+ /** A test that its describe's `beforeEach` mounted the wrapper for, mounting it first itself. */
1015
+ private async mountedFirst(test: J.Block): Promise<J.Block> {
1016
+ const hooked = hookMounts.get(test.id);
1017
+ if (!hooked) return test;
1018
+ const [first, ...rest] = test.statements;
1019
+ const cursor = new Cursor(first.element, new Cursor(test, this.cursor.parent));
1020
+ // A copy for each test, whose ids the converter keeps apart
1021
+ const declare = Template.builder().code(`const ${hooked.name} = `).param(withNewIds(hooked.mount)).build();
1022
+ const declared = await declare.apply(first.element, cursor) as J.VariableDeclarations | undefined;
1023
+ if (!declared) throw new Error(`Cannot declare ${hooked.name}`);
1024
+ mounts.push(declared.variables[0].element.initializer!.element.id);
1025
+ const semicolon = test.statements.some(padded => padded.markers.markers.some(marker => marker.kind === J.Markers.Semicolon));
1026
+ const padded = {...first, element: {...declared, prefix: first.element.prefix},
1027
+ markers: {...first.markers, markers: semicolon ? [{kind: J.Markers.Semicolon, id: randomId()}] : []}};
1028
+ return create(test, draft => {
1029
+ draft.statements = [padded, first, ...rest] as any;
1030
+ });
1031
+ }
1032
+ }().visit<J.Block>(trimmed, ctx, this.cursor.parent);
1033
+ return {candidate: candidate!, mounts};
1034
+ }
1035
+
1036
+ private saveState() {
1037
+ return {mounts: new Map(this.mounts), uses: new Map(this.uses), removedStatements: new Set(this.removedStatements),
1038
+ unmounts: new Set(this.unmounts), declarations: new Set(this.declarations), pending: new Set(this.pending),
1039
+ reformat: new Set(this.reformat), hoists: new Map(this.hoists), hoistedMounts: new Map(this.hoistedMounts),
1040
+ portals: new Set(this.portals), rows: this.rows.length, afterVisit: this.afterVisit.length, blockers: new Map(this.blockers)};
1041
+ }
1042
+
1043
+ private restoreState(saved: ReturnType<typeof this.saveState>): void {
1044
+ const refill = <T>(target: Set<T>, from: Set<T>) => {
1045
+ target.clear();
1046
+ from.forEach(value => target.add(value));
1047
+ };
1048
+ const remap = <K, V>(target: Map<K, V>, from: Map<K, V>) => {
1049
+ target.clear();
1050
+ from.forEach((value, key) => target.set(key, value));
1051
+ };
1052
+ remap(this.mounts, saved.mounts);
1053
+ remap(this.uses, saved.uses);
1054
+ remap(this.hoists, saved.hoists);
1055
+ remap(this.hoistedMounts, saved.hoistedMounts);
1056
+ remap(this.blockers, saved.blockers);
1057
+ [[this.removedStatements, saved.removedStatements], [this.unmounts, saved.unmounts], [this.declarations, saved.declarations],
1058
+ [this.pending, saved.pending], [this.reformat, saved.reformat], [this.portals, saved.portals]]
1059
+ .forEach(([target, from]) => refill(target, from));
1060
+ this.rows.length = saved.rows;
1061
+ this.afterVisit.length = saved.afterVisit;
1062
+ }
1063
+
1064
+ private async convertBlock(block: J.Block, ctx: ExecutionContext): Promise<J | undefined> {
748
1065
  const planned: string[] = [];
749
1066
  const apis: Render[] = [];
750
1067
  for (const statement of block.statements) {
@@ -754,15 +1071,25 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
754
1071
  const reads = READS[api];
755
1072
  // React 15 marks its markup with `data-reactroot` and empty renders with comments, which Enzyme's html() leaves out
756
1073
  const markup = this.reactMajor >= 16;
1074
+ let blocking: Parameters<typeof blockedByUses>[0] | undefined;
757
1075
  const scope = analyzeWrapperScope(this.cursor, candidate, {events: reads.simulate ? this.events.events : new Set(), html: reads.html && markup, untaggedPositions, hostNames, snapshots: snapshots && markup, optionalChaining: this.optionalChaining,
758
- constant: node => this.constantString(node)});
759
- if (!scope) continue;
760
- if ([...scope.uses.values()].some(use => use.use === "setProps" && !reads.props(use.props!, this.importedNames))) continue;
1076
+ constant: node => this.constantString(node), blocked: references => blocking = references});
1077
+ if (!scope) {
1078
+ if (blocking) this.blockers.set(candidate.mount.id, await blockedByUses(blocking));
1079
+ continue;
1080
+ }
1081
+ if ([...scope.uses.values()].some(use => use.use === "setProps" && !reads.props(use.props!, this.importedNames))) {
1082
+ this.blockers.set(candidate.mount.id, blockedByGate("setProps"));
1083
+ continue;
1084
+ }
761
1085
  const mount = new Cursor(candidate.mount, variableCursor(this.cursor, candidate.declaration));
762
1086
  const document = documentAt(mount);
763
1087
  if (!document || !await renderPatterns[api].render.match(candidate.mount, mount)) continue;
764
1088
  const attached = this.events.attached && [...scope.uses.values()].some(use => use.use === "simulate");
765
- if (!attached && this.rootStyles && [...scope.uses.values()].some(use => CONTAINER_READS.has(use.use))) continue;
1089
+ if (!attached && this.rootStyles && [...scope.uses.values()].some(use => CONTAINER_READS.has(use.use))) {
1090
+ this.blockers.set(candidate.mount.id, blockedByGate("rootStyles"));
1091
+ continue;
1092
+ }
766
1093
  this.mounts.set(candidate.mount.id, {document, api, attached});
767
1094
  apis.push(api);
768
1095
  this.declarations.add(candidate.declaration.id);
@@ -1010,9 +1337,16 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
1010
1337
  if (node?.kind !== J.Kind.MethodInvocation) return undefined;
1011
1338
  const call = node as J.MethodInvocation;
1012
1339
  const api = enzymeMethod(call);
1013
- if (api === "mount") return read && this.rendersPortal(call) ? undefined : api;
1340
+ if (api === "mount") {
1341
+ if (!read || !this.rendersPortal(call)) return api;
1342
+ this.blockers.set(call.id, blockedByGate("portal"));
1343
+ return undefined;
1344
+ }
1345
+ if (api !== "shallow" || call.arguments.elements.length !== 1) return undefined;
1014
1346
  const element = call.arguments.elements[0]?.element;
1015
- return api === "shallow" && call.arguments.elements.length === 1 && rendersHostElements(element, this.imports, scanned.components, this.importedNames, this.declaredHost) ? api : undefined;
1347
+ if (rendersHostElements(element, this.imports, scanned.components, this.importedNames, this.declaredHost)) return api;
1348
+ this.blockers.set(call.id, blockedByGate("shallow"));
1349
+ return undefined;
1016
1350
  }
1017
1351
 
1018
1352
  /**
@@ -1067,7 +1401,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
1067
1401
 
1068
1402
  async recipeList() {
1069
1403
  const steps = this.dependencySteps;
1070
- return [...steps ? [steps.rtl, steps.rtl18, steps.dom18] : [], new FindEnzymeUsage()];
1404
+ // The peer `@testing-library/dom` goes first, so RTL 16 lands only where it did
1405
+ return [...steps ? [steps.rtl, steps.dom18, steps.rtl18] : [], new FindEnzymeUsage()];
1071
1406
  }
1072
1407
  }
1073
1408
 
@@ -26,6 +26,15 @@ export class EnzymeUsageRow {
26
26
  suggestedAction!: string;
27
27
  }
28
28
 
29
+ /**
30
+ * What kept each render the converter analyzed on Enzyme, by source and then mount, for the review row of the mount that
31
+ * `FindEnzymeUsage` writes after it. Both run in the same RPC worker, which edits a source with each recipe in turn.
32
+ */
33
+ export const RENDER_BLOCKERS = new Map<string, ReadonlyMap<string, string>>();
34
+
35
+ /** The key of {@link RENDER_BLOCKERS} for what keeps every render of a source on Enzyme. */
36
+ export const FILE_BLOCKER = "*";
37
+
29
38
  export function enzymeModule(value: unknown): value is string {
30
39
  return typeof value === "string" && (value === ENZYME || value.startsWith("enzyme/") ||
31
40
  (value === "enzyme-to-json" || value.startsWith("enzyme-to-json/")) || /^(?:@[^/]+\/)?enzyme-adapter-/.test(value));
@@ -43,17 +52,29 @@ export function enzymeWrapper(type: Type | undefined): boolean {
43
52
  name => /^enzyme\.(?:ReactWrapper|ShallowWrapper|CommonWrapper)$/.test(name));
44
53
  }
45
54
 
46
- export function migrationReason(api: string): {reason: string, suggestedAction: string} {
47
- if (api === "shallow" || api === "dive") {
55
+ /** What an Enzyme `find`, `findWhere` or `filterWhere` matches by, which says how RTL queries the same elements. */
56
+ export type SelectorKind = "component" | "dom" | "enzyme" | "props" | "predicate";
57
+
58
+ /** What a `simulate` dispatches, which says what `fireEvent` needs to dispatch the same. */
59
+ export type EventKind = "event" | "hover" | "change" | "mock" | "other";
60
+
61
+ export function migrationReason(api: string, selector?: SelectorKind, event?: EventKind): {reason: string, suggestedAction: string} {
62
+ if (api === "dive") {
63
+ return {reason: "SHALLOW_RENDERING", suggestedAction: "Remove the `dive()`: RTL's `render` renders every level, so query what the child component renders directly. " +
64
+ "Where the test relied on the levels below not rendering, `jest.mock` those components' modules with stubs."};
65
+ }
66
+ if (api === "shallow") {
48
67
  return {reason: "SHALLOW_RENDERING", suggestedAction: "Review child rendering and effects before replacing shallow rendering with RTL render."};
49
68
  }
50
69
  const internal = INTERNAL_STATE_ACTIONS[api];
51
70
  if (internal) return {reason: "INTERNAL_STATE", suggestedAction: internal};
52
71
  if (api === "simulate") {
53
- return {reason: "UNSUPPORTED_EVENT", suggestedAction: "Review event payloads and async control flow before selecting user-event or fireEvent."};
72
+ return {reason: "UNSUPPORTED_EVENT", suggestedAction: event && EVENT_ACTIONS[event] ||
73
+ "Review event payloads and async control flow before selecting user-event or fireEvent."};
54
74
  }
55
75
  if (api === "find" || api === "findWhere" || api === "filterWhere") {
56
- return {reason: "SELECTOR_REVIEW", suggestedAction: "Review selector scope, component versus DOM matching, and zero/one/multiple-match behavior."};
76
+ return {reason: "SELECTOR_REVIEW", suggestedAction: selector && SELECTOR_ACTIONS[selector] ||
77
+ "Review selector scope, component versus DOM matching, and zero/one/multiple-match behavior."};
57
78
  }
58
79
  if (api === "mount") {
59
80
  return {reason: "RENDER_REVIEW", suggestedAction: "Review every use of the wrapper and its shared setup before replacing mount with RTL render."};
@@ -76,6 +97,22 @@ const INTERNAL_STATE_ACTIONS: Readonly<Record<string, string>> = {
76
97
  invoke: "Fire the DOM event that calls the handler, with `fireEvent` or `userEvent`, instead of invoking the prop."
77
98
  };
78
99
 
100
+ const SELECTOR_ACTIONS: Readonly<Record<SelectorKind, string>> = {
101
+ component: "RTL has no component tree: query the element this component renders by its role, label or text, with `screen.getByRole` or `getByText`. To check the props it receives, `jest.mock` its module and assert on the mock's calls.",
102
+ dom: "The selector reads the same in `container.querySelectorAll`, which the recipe writes once the render converts: another use of this render keeps it on Enzyme, so see the other rows of this test. Enzyme also counts components given the same class, id or attribute.",
103
+ enzyme: "Rewrite the selector for `querySelectorAll`: Enzyme compares `[attr=value]` with the prop's own value rather than its string, and `>`, `+` and `~` count the components between elements. Name the tag, class or string attribute the element renders, or query it with `screen.getByRole`.",
104
+ props: "Enzyme matches these props on components as well as elements. Query the element by the attribute they render, such as `[name=\"email\"]` in `querySelectorAll`, or by its role or label; a prop that renders no attribute has no DOM query.",
105
+ predicate: "Filter `Array.from(container.querySelectorAll(tag))` by what the predicate reads in the DOM, such as `textContent` or an attribute, or query with `screen.getByText`. A predicate on props or component type has no DOM equivalent."
106
+ };
107
+
108
+ const EVENT_ACTIONS: Readonly<Record<EventKind, string>> = {
109
+ event: "`fireEvent` dispatches this event as it is, which the recipe writes once the render converts: another use of this render keeps it on Enzyme, so see the other rows of this test.",
110
+ hover: "Write `fireEvent` with this event on React 17 and later. React 15 and 16 make `onMouseEnter` and `onMouseLeave` of `mouseover` and `mouseout`, so there use `userEvent.hover` or `userEvent.unhover`, and expect `onMouseOver` and `onMouseOut` to run as well.",
111
+ change: "Enzyme calls `onChange` without changing the input. Set what the handler reads: `fireEvent.change(input, {target: {value: 'text'}})`, or `fireEvent.click(input)` for a checkbox or radio button, whose `onChange` React runs on click.",
112
+ mock: "Enzyme merges the mock into the event the handler gets, where `fireEvent` sets only real event properties. Set an input's value with `fireEvent.change` before firing rather than mocking `target`, and replace a `preventDefault: jest.fn()` with a check that `fireEvent` returned `false`.",
113
+ other: "Dispatch it with the `fireEvent` method named for the React event without `on`, such as `fireEvent.contextMenu`. Unlike `simulate`, `fireEvent` dispatches a real DOM event, which bubbles and runs the element's default action."
114
+ };
115
+
79
116
  const WRAPPER_API_ACTIONS: Readonly<Record<string, string>> = {
80
117
  prop: "Assert what the prop produces in the DOM, such as text, an attribute, or a role. For a callback prop, fire the event that calls it and assert on a `jest.fn()`.",
81
118
  props: "Assert what the props produce in the DOM. To check what a child component receives, mock that component with `jest.mock` and assert on the mock's calls.",
@@ -90,7 +127,27 @@ const WRAPPER_API_ACTIONS: Readonly<Record<string, string>> = {
90
127
  hasClass: "Use `element.classList.contains`, or `toHaveClass` from `@testing-library/jest-dom`.",
91
128
  getDOMNode: "Query the element directly with `screen.getBy*` or `container.querySelector`; RTL already returns DOM nodes.",
92
129
  update: "Remove it: RTL renders the latest state on every query. Await `findBy*` or `waitFor` where the change is asynchronous.",
93
- unmount: "Call the `unmount` that RTL's `render` returns, or rely on RTL's automatic cleanup after each test."
130
+ unmount: "Call the `unmount` that RTL's `render` returns, or rely on RTL's automatic cleanup after each test.",
131
+ hostNodes: "Remove it: `querySelectorAll` and the `getBy*` queries return DOM elements only, which is what `hostNodes()` keeps.",
132
+ childAt: "Read the queried element's `children[index]`, or query the child with `within(element)`.",
133
+ get: "Index the `querySelectorAll` or `getAllBy*` result; it already holds DOM elements, which `get` returns a React element in place of.",
134
+ forEach: "Loop over `Array.from(container.querySelectorAll(selector))` or the `getAllBy*` result, reading each element's DOM properties.",
135
+ map: "Map over `Array.from(container.querySelectorAll(selector))` or the `getAllBy*` result, reading each element's DOM properties.",
136
+ reduce: "Reduce over `Array.from(container.querySelectorAll(selector))` or the `getAllBy*` result, reading each element's DOM properties.",
137
+ filter: "Filter `Array.from(container.querySelectorAll(selector))` by a DOM property, or narrow the selector so the query returns only those elements.",
138
+ contains: "Assert the element is in the DOM: `screen.getByText` or `getByRole` for what the React element renders, or `toContainElement` from `@testing-library/jest-dom`.",
139
+ containsMatchingElement: "Assert what the element renders is in the DOM, with `screen.getByText` or `getByRole`; RTL doesn't compare React elements.",
140
+ is: "Use `element.matches(selector)` on the queried element.",
141
+ type: "Read the element's `tagName` for a DOM element. A component's type has no DOM equivalent: assert on what it renders.",
142
+ name: "Read the element's `tagName` for a DOM element. A component's name has no DOM equivalent: assert on what it renders.",
143
+ parent: "Read the queried element's `parentElement`.",
144
+ closest: "Use `element.closest(selector)` on the queried element.",
145
+ isEmptyRender: "Assert `container` is empty, with `expect(container).toBeEmptyDOMElement()` from `@testing-library/jest-dom` or `container.innerHTML === ''`.",
146
+ debug: "Use `screen.debug()` or `prettyDOM(element)`, or remove it once the test passes.",
147
+ getElement: "Assert on what the element renders in the DOM; RTL has no React element tree to compare.",
148
+ renderProp: "Render what the render prop returns by rendering the component with that prop, and query the result in the DOM.",
149
+ detach: "Remove it: RTL unmounts and removes each render's container after each test.",
150
+ key: "A React key has no DOM equivalent: assert on the order or content of the rendered elements instead."
94
151
  };
95
152
 
96
153
  export function enclosingScope(start: Cursor): string {