@openrewrite/recipes-react 0.19.0 → 0.20.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 (39) hide show
  1. package/dist/search/find-enzyme-usage.d.ts.map +1 -1
  2. package/dist/search/find-enzyme-usage.js +34 -1
  3. package/dist/search/find-enzyme-usage.js.map +1 -1
  4. package/dist/testing/enzyme-shared-wrapper.d.ts +26 -0
  5. package/dist/testing/enzyme-shared-wrapper.d.ts.map +1 -0
  6. package/dist/testing/enzyme-shared-wrapper.js +213 -0
  7. package/dist/testing/enzyme-shared-wrapper.js.map +1 -0
  8. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  9. package/dist/testing/enzyme-to-react-testing-library.js +276 -0
  10. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  11. package/dist/testing/enzyme-usage.d.ts +3 -1
  12. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  13. package/dist/testing/enzyme-usage.js +19 -3
  14. package/dist/testing/enzyme-usage.js.map +1 -1
  15. package/dist/testing/enzyme-wrapper-scope.d.ts +2 -0
  16. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  17. package/dist/testing/enzyme-wrapper-scope.js +12 -6
  18. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  19. package/dist/zustand/redux-stores.d.ts +10 -0
  20. package/dist/zustand/redux-stores.d.ts.map +1 -1
  21. package/dist/zustand/redux-stores.js +147 -5
  22. package/dist/zustand/redux-stores.js.map +1 -1
  23. package/dist/zustand/redux-to-zustand.d.ts +20 -5
  24. package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
  25. package/dist/zustand/redux-to-zustand.js +518 -26
  26. package/dist/zustand/redux-to-zustand.js.map +1 -1
  27. package/dist/zustand/zustand-plan.d.ts +27 -4
  28. package/dist/zustand/zustand-plan.d.ts.map +1 -1
  29. package/dist/zustand/zustand-plan.js +250 -15
  30. package/dist/zustand/zustand-plan.js.map +1 -1
  31. package/package.json +1 -1
  32. package/src/search/find-enzyme-usage.ts +32 -3
  33. package/src/testing/enzyme-shared-wrapper.ts +224 -0
  34. package/src/testing/enzyme-to-react-testing-library.ts +265 -2
  35. package/src/testing/enzyme-usage.ts +27 -3
  36. package/src/testing/enzyme-wrapper-scope.ts +11 -4
  37. package/src/zustand/redux-stores.ts +160 -5
  38. package/src/zustand/redux-to-zustand.ts +555 -34
  39. package/src/zustand/zustand-plan.ts +267 -12
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@openrewrite/recipes-react",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "license": "Moderne Source Available License",
5
5
  "description": "OpenRewrite recipes for React.",
6
6
  "homepage": "https://github.com/openrewrite/rewrite",
@@ -1,7 +1,36 @@
1
1
  import {and, check, not, or, DataTable, ExecutionContext, foundSearchResult, Recipe, RecipeRef, TreeVisitor} from "@openrewrite/rewrite";
2
- import {isVendoredOrBundled, JavaScriptVisitor, JS, usesMethod, usesType} from "@openrewrite/rewrite/javascript";
2
+ import {isObjectLiteral, isVendoredOrBundled, JavaScriptVisitor, JS, usesMethod, usesType} from "@openrewrite/rewrite/javascript";
3
3
  import {isIdentifier, J, Type, TypedTree} from "@openrewrite/rewrite/java";
4
- import {enclosingScope, ENZYME_GUIDE, ENZYME_USAGE_TABLE, enzymeMethod, enzymeModule, enzymeWrapper, EnzymeUsageRow, migrationReason} from "../testing/enzyme-usage";
4
+ import {enclosingScope, ENZYME_GUIDE, ENZYME_USAGE_TABLE, enzymeMethod, enzymeModule, enzymeWrapper, EnzymeUsageRow, EventKind, migrationReason, SelectorKind} from "../testing/enzyme-usage";
5
+ import {domSelector, objectProperties, simulatedEvent} from "../testing/enzyme-wrapper-scope";
6
+
7
+ function eventKind(api: string, [name, mock]: J[]): EventKind | undefined {
8
+ if (api !== "simulate" || name?.kind !== J.Kind.Literal || typeof (name as J.Literal).value !== "string") return undefined;
9
+ const event = simulatedEvent((name as J.Literal).value as string);
10
+ if (!event) return "other";
11
+ if (event === "change") return "change";
12
+ const properties = mock && mock.kind !== J.Kind.Empty ? objectProperties(mock) : new Map();
13
+ // A key for a key event, or a native event, is what the converter dispatches as well
14
+ const dispatched = properties?.size === 0 || properties?.size === 1 && (properties.has("nativeEvent") ||
15
+ (event === "keyDown" || event === "keyUp") && properties.has("key"));
16
+ if (!dispatched) return "mock";
17
+ return ["mouseEnter", "mouseLeave", "mouseOver", "mouseOut"].includes(event) ? "hover" : "event";
18
+ }
19
+
20
+ function selectorKind(api: string, selector: J | undefined): SelectorKind | undefined {
21
+ if (api === "findWhere" || api === "filterWhere") return "predicate";
22
+ if (api !== "find" || !selector) return undefined;
23
+ if (selector.kind === J.Kind.Literal) {
24
+ const value = (selector as J.Literal).value;
25
+ if (typeof value !== "string") return undefined;
26
+ // Enzyme reads a selector starting with a capital as a component's display name
27
+ return /^[A-Z]/.test(value) ? "component" : domSelector(value) ? "dom" : "enzyme";
28
+ }
29
+ if (isObjectLiteral(selector)) return "props";
30
+ const name = isIdentifier(selector) ? selector.simpleName :
31
+ selector.kind === J.Kind.FieldAccess ? (selector as J.FieldAccess).name.element.simpleName : undefined;
32
+ return name && /^[A-Z]/.test(name) && TypedTree.getType(selector) !== Type.Primitive.String ? "component" : undefined;
33
+ }
5
34
 
6
35
  /**
7
36
  * Inventories imports/setup even when types are unavailable; calls and wrapper fields are
@@ -70,7 +99,7 @@ export class FindEnzymeUsage extends Recipe {
70
99
  }
71
100
  const api = enzymeMethod(method);
72
101
  if (!api) return result;
73
- const {reason, suggestedAction} = migrationReason(api);
102
+ const {reason, suggestedAction} = migrationReason(api, selectorKind(api, args[0]), eventKind(api, args));
74
103
  return this.report(result, api, reason, suggestedAction, ctx);
75
104
  }
76
105
 
@@ -0,0 +1,224 @@
1
+ import {Cursor, randomId} from "@openrewrite/rewrite";
2
+ import {JS, referencesOf} from "@openrewrite/rewrite/javascript";
3
+ import {isIdentifier, J} from "@openrewrite/rewrite/java";
4
+ import {mountedElement, variableCursor} from "./enzyme-wrapper-scope";
5
+
6
+ /** A `let` wrapper that each test of its block mounts for itself, and the `afterEach` that cleans it up, if there is one. */
7
+ export interface SharedWrapper {
8
+ declaration: J.VariableDeclarations;
9
+ name: string;
10
+ afterEach?: J;
11
+ /** The statements of the `afterEach` that unmount or clear the wrapper, or its expression body when that does. */
12
+ cleanup: ReadonlySet<string>;
13
+ /** The cleanup statements that unmount the wrapper. */
14
+ unmounts: ReadonlySet<string>;
15
+ /** The `wrapper = mount(...)` statements, each the first use of the wrapper in its test. */
16
+ assignments: ReadonlySet<string>;
17
+ /** The `wrapper = null` statements of the tests, after which a test no longer reads the wrapper. */
18
+ clears: ReadonlySet<string>;
19
+ /** The bodies of the tests that a `beforeEach` of their describe mounts the wrapper for, with that mount. */
20
+ hookMounts: ReadonlyMap<string, J.MethodInvocation>;
21
+ /** Those `beforeEach` mounts: the hook where it does nothing else, or else the mounting statement. */
22
+ hookRemovals: ReadonlySet<string>;
23
+ /** Each such hook, as it was, with the describe it is in, its mounting statement and the bodies of its tests. */
24
+ hooks: readonly SharedHook[];
25
+ }
26
+
27
+ export interface SharedHook {
28
+ owner: string;
29
+ hook: J;
30
+ /** The statements of its describe before it, and the prefix each statement of the describe had. */
31
+ before: readonly string[];
32
+ prefixes: ReadonlyMap<string, J["prefix"]>;
33
+ mounting: string;
34
+ tests: readonly string[];
35
+ }
36
+
37
+ /** A copy of a tree with new ids, which a tree copied into several places needs, sharing its types. */
38
+ export function withNewIds<T>(node: T): T {
39
+ if (Array.isArray(node)) return node.map(withNewIds) as T;
40
+ if (node === null || typeof node !== "object") return node;
41
+ const kind = (node as any).kind;
42
+ if (typeof kind === "string" && kind.startsWith("org.openrewrite.java.tree.JavaType")) return node;
43
+ const copy: any = {};
44
+ for (const [key, value] of Object.entries(node)) {
45
+ copy[key] = key === "id" && typeof value === "string" ? randomId() :
46
+ key === "type" || key === "methodType" || key === "fieldType" || key === "variableType" ? value : withNewIds(value);
47
+ }
48
+ return copy;
49
+ }
50
+
51
+ function describeBody(statement: J): J.Block | undefined {
52
+ const call = expressionOf(statement);
53
+ if (call.kind !== J.Kind.MethodInvocation) return undefined;
54
+ const body = callback(call as J.MethodInvocation, ["describe"])?.body;
55
+ return body?.kind === J.Kind.Block ? body as J.Block : undefined;
56
+ }
57
+
58
+ export function expressionOf(statement: J): J {
59
+ return statement.kind === JS.Kind.ExpressionStatement ? (statement as JS.ExpressionStatement).expression : statement;
60
+ }
61
+
62
+ function callback(call: J.MethodInvocation, names: readonly string[]): J.Lambda | undefined {
63
+ if (call.select || !names.includes(call.name.simpleName)) return undefined;
64
+ // A hook takes its function first, a test or describe after its name
65
+ const argument = call.arguments.elements[names[0] === "afterEach" || names[0] === "beforeEach" ? 0 : 1]?.element;
66
+ return argument?.kind === JS.Kind.ArrowFunction ? (argument as JS.ArrowFunction).lambda : undefined;
67
+ }
68
+
69
+ function named(node: J | undefined, name: string): boolean {
70
+ return node !== undefined && isIdentifier(node) && node.simpleName === name;
71
+ }
72
+
73
+ /** `wrapper.unmount()` or `wrapper?.unmount()`. */
74
+ function unmountOf(node: J | undefined, name: string): boolean {
75
+ if (node?.kind !== J.Kind.MethodInvocation) return false;
76
+ const call = node as J.MethodInvocation;
77
+ return call.name.simpleName === "unmount" && named(call.select?.element, name) &&
78
+ call.arguments.elements.every(argument => argument.element.kind === J.Kind.Empty);
79
+ }
80
+
81
+ /** `wrapper = null` or `wrapper = undefined`. */
82
+ function clearOf(node: J, name: string): boolean {
83
+ if (node.kind !== J.Kind.Assignment) return false;
84
+ const {variable, assignment} = node as J.Assignment;
85
+ const value = assignment.element;
86
+ // NOTE: a `null` literal from the RPC host carries no value, only its source
87
+ return named(variable, name) && (value.kind === J.Kind.Literal && (value as J.Literal).valueSource === "null" || named(value, "undefined"));
88
+ }
89
+
90
+ /** An unmount of the wrapper, alone or under `if (wrapper)`, with or without braces. */
91
+ function unmountStatement(statement: J, name: string): boolean {
92
+ if (statement.kind !== J.Kind.If) return unmountOf(expressionOf(statement), name);
93
+ const guard = statement as J.If;
94
+ if (guard.elsePart || !named(guard.ifCondition.tree.element, name)) return false;
95
+ let then: J = guard.thenPart.element;
96
+ if (then.kind === J.Kind.Block) {
97
+ const statements = (then as J.Block).statements;
98
+ if (statements.length !== 1) return false;
99
+ then = statements[0].element;
100
+ }
101
+ return unmountOf(expressionOf(then), name);
102
+ }
103
+
104
+ /**
105
+ * A wrapper declared without a value whose every use is in a test, of the same block or a describe within it, that
106
+ * starts by mounting it, as in `wrapper = mount(<Panel />);`, in a `beforeEach` that ends by mounting it for the tests
107
+ * of its describe, or in the `afterEach` statements that unmount or clear it. Each test's wrapper is then its own,
108
+ * which a `const` in the test declares as well, and RTL unmounts every render after each test.
109
+ */
110
+ export function sharedWrapper(block: Cursor, statement: J): SharedWrapper | undefined {
111
+ if (statement.kind !== J.Kind.VariableDeclarations) return undefined;
112
+ const declaration = statement as J.VariableDeclarations;
113
+ if (declaration.variables.length !== 1 || declaration.leadingAnnotations.length > 0 ||
114
+ !declaration.modifiers.some(modifier => modifier.keyword === "let")) return undefined;
115
+ const variable = declaration.variables[0].element;
116
+ if (!isIdentifier(variable.name) || variable.initializer) return undefined;
117
+ const name = variable.name.simpleName;
118
+ let afterEach: J | undefined;
119
+ const cleanup = new Set<string>();
120
+ const unmounts = new Set<string>();
121
+ const assignments = new Set<string>();
122
+ const clears = new Set<string>();
123
+ const mounted = new Set<string>();
124
+ const cleared = new Set<string>();
125
+ // The describes whose tests mount the wrapper themselves, and those whose `beforeEach` mounts it
126
+ const ownMounts = new Set<string>();
127
+ const hooks = new Map<string, {owner: J.Block, hook: J, mount: J.MethodInvocation, mounting: string, removal: string}>();
128
+ for (const reference of referencesOf(new Cursor(variable.name, variableCursor(block, declaration)), name, "value")) {
129
+ if (reference.identifier === variable.name) continue;
130
+ if (reference.declares) return undefined;
131
+ const trees: Cursor[] = [];
132
+ let c = reference.cursor.parentTree();
133
+ for (; c && c.value !== block.value; c = c.parentTree()) trees.push(c);
134
+ if (!c || trees.length === 0) return undefined;
135
+ // The statement of the block, or of the describes within it, that holds the reference
136
+ let level = trees.length - 1;
137
+ let owner = block.value as J.Block;
138
+ for (let body = describeBody(trees[level].value as J); body; body = describeBody(trees[level].value as J)) {
139
+ const at = trees.findIndex(tree => tree.value === body);
140
+ if (at < 1) return undefined;
141
+ owner = body;
142
+ level = at - 1;
143
+ }
144
+ const top = trees[level].value as J;
145
+ const call = expressionOf(top);
146
+ if (call.kind !== J.Kind.MethodInvocation) return undefined;
147
+ const before = callback(call as J.MethodInvocation, ["beforeEach"]);
148
+ if (before) {
149
+ // The hook's last statement mounts the wrapper, so each test of the describe can mount it first instead
150
+ if (before.body.kind !== J.Kind.Block || hooks.has(owner.id) || ownMounts.has(owner.id) || !reference.writes) return undefined;
151
+ const body = before.body as J.Block;
152
+ const mounting = trees[trees.findIndex(tree => tree.value === body) - 1]?.value as J | undefined;
153
+ if (!mounting || mounting !== body.statements[body.statements.length - 1]?.element) return undefined;
154
+ const assignment = expressionOf(mounting);
155
+ if (assignment.kind !== J.Kind.Assignment || (assignment as J.Assignment).variable !== reference.identifier) return undefined;
156
+ const mount = (assignment as J.Assignment).assignment.element;
157
+ if (mount.kind !== J.Kind.MethodInvocation || !mountedElement(mount as J.MethodInvocation)) return undefined;
158
+ hooks.set(owner.id, {owner, hook: top, mount: mount as J.MethodInvocation, mounting: mounting.id, removal: body.statements.length === 1 ? top.id : mounting.id});
159
+ continue;
160
+ }
161
+ const after = callback(call as J.MethodInvocation, ["afterEach"]);
162
+ if (after) {
163
+ if (owner !== block.value || afterEach && afterEach !== top) return undefined;
164
+ afterEach = top;
165
+ // The statement of the callback the reference is in, or its expression body
166
+ const at = after.body.kind === J.Kind.Block ? trees.findIndex(tree => tree.value === after.body) - 1 : trees.findIndex(tree => tree.value === after.body);
167
+ const cleaning = trees[at]?.value as J | undefined;
168
+ if (!cleaning) return undefined;
169
+ if (unmountStatement(cleaning, name)) unmounts.add(cleaning.id);
170
+ else if (!clearOf(expressionOf(cleaning), name)) return undefined;
171
+ cleanup.add(cleaning.id);
172
+ continue;
173
+ }
174
+ const test = callback(call as J.MethodInvocation, ["it", "test"]);
175
+ if (test?.body.kind !== J.Kind.Block) return undefined;
176
+ const body = test.body as J.Block;
177
+ if (hooks.has(owner.id)) {
178
+ if (reference.writes) return undefined;
179
+ continue;
180
+ }
181
+ if (cleared.has(body.id)) return undefined;
182
+ const assignment = trees[0].value as J;
183
+ const parent = trees[1]?.value as J | undefined;
184
+ const inBody = parent === body || parent?.kind === JS.Kind.ExpressionStatement && trees[2]?.value === body;
185
+ if (mounted.has(body.id)) {
186
+ if (!reference.writes) continue;
187
+ // Clearing the wrapper in a test is only for the afterEach, which no longer unmounts it
188
+ if (!inBody || !clearOf(assignment, name)) return undefined;
189
+ clears.add((parent === body ? assignment : parent!).id);
190
+ cleared.add(body.id);
191
+ continue;
192
+ }
193
+ // The first use in a test mounts the wrapper as a statement of the test's body
194
+ if (!reference.writes || assignment.kind !== J.Kind.Assignment || (assignment as J.Assignment).variable !== reference.identifier || !inBody) return undefined;
195
+ const mount = (assignment as J.Assignment).assignment.element;
196
+ if (mount.kind !== J.Kind.MethodInvocation || !mountedElement(mount as J.MethodInvocation)) return undefined;
197
+ assignments.add(assignment.id);
198
+ mounted.add(body.id);
199
+ ownMounts.add(owner.id);
200
+ }
201
+ const hookMounts = new Map<string, J.MethodInvocation>();
202
+ const hookRemovals = new Set<string>();
203
+ const sharedHooks: SharedHook[] = [];
204
+ for (const {owner, hook, mount, mounting, removal} of hooks.values()) {
205
+ const tests: string[] = [];
206
+ // Every test of the describe mounts, as the hook ran for each, and no nested describe or later hook runs between
207
+ const statements = owner.statements.map(statement => statement.element);
208
+ for (const [i, statement] of statements.entries()) {
209
+ const call = expressionOf(statement);
210
+ if (call.kind !== J.Kind.MethodInvocation) continue;
211
+ if (describeBody(statement) || i > statements.indexOf(hook) && callback(call as J.MethodInvocation, ["beforeEach"])) return undefined;
212
+ const test = callback(call as J.MethodInvocation, ["it", "test"]);
213
+ if (!test) continue;
214
+ if (test.body.kind !== J.Kind.Block || (test.body as J.Block).statements.length === 0) return undefined;
215
+ hookMounts.set(test.body.id, mount);
216
+ tests.push(test.body.id);
217
+ }
218
+ hookRemovals.add(removal);
219
+ sharedHooks.push({owner: owner.id, hook, before: statements.slice(0, statements.indexOf(hook)).map(statement => statement.id),
220
+ prefixes: new Map(statements.map(statement => [statement.id, statement.prefix])), mounting, tests});
221
+ }
222
+ return assignments.size > 0 || hookMounts.size > 0 ?
223
+ {declaration, name, afterEach, cleanup, unmounts, assignments, clears, hookMounts, hookRemovals, hooks: sharedHooks} : undefined;
224
+ }
@@ -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";
@@ -15,6 +15,7 @@ import {HostComponents, hostComponentExports, hostComponentsDeclared, ImportedEx
15
15
  import {moduleFacts, Modules, rendersPortal, resolver} from "./enzyme-portals";
16
16
  import {evaluate, stringParts} from "./enzyme-constant-strings";
17
17
  import {hostOnlyNames, selectorNames, SelectorNames} from "./enzyme-selector-names";
18
+ import {expressionOf, SharedHook, SharedWrapper, sharedWrapper, withNewIds} from "./enzyme-shared-wrapper";
18
19
  import {analyzeWrapperScope, SIMULATED_EVENTS, idsWithin, innermostCall, mountedElement, passesRef, selectorLiteral, simpleChain, statementPosition, throwingPosition, variableCursor, withoutEnzymeTypes, withRenderOptionsOnElementLine, wrapperDeclaration, WrapperRead, WrapperUse} from "./enzyme-wrapper-scope";
19
20
 
20
21
  const RTL = "@testing-library/react";
@@ -476,6 +477,31 @@ function declaredVersion(version: string | undefined): Declaration {
476
477
  return {major: Number(match[2]), minor: /^\d+$/.test(match[3] ?? "") ? Number(match[3]) : undefined};
477
478
  }
478
479
 
480
+ /** The statements with `statement` after the last of them that was before it. */
481
+ function inserted<T extends {element: J}>(statements: readonly T[], before: readonly string[], statement: T): T[] {
482
+ const at = statements.reduce((last, padded, i) => before.includes(padded.element.id) ? i + 1 : last, 0);
483
+ return [...statements.slice(0, at), statement, ...statements.slice(at)];
484
+ }
485
+
486
+ /** The statements with the prefixes they had before others were taken out of their block and put back. */
487
+ function withPrefixes<T extends {element: J}>(statements: readonly T[], prefixes: ReadonlyMap<string, J["prefix"]>): T[] {
488
+ return statements.map(padded => {
489
+ const prefix = prefixes.get(padded.element.id);
490
+ return prefix && prefix !== padded.element.prefix ? {...padded, element: {...padded.element, prefix}} : padded;
491
+ });
492
+ }
493
+
494
+ /** The block without the statements of `removed`, its first statement keeping the block's first prefix. */
495
+ function withoutStatements(block: J.Block, removed: ReadonlySet<string>): J.Block {
496
+ if (!block.statements.some(statement => removed.has(statement.element.id))) return block;
497
+ const kept = block.statements.filter(statement => !removed.has(statement.element.id));
498
+ const first = block.statements[0].element.prefix;
499
+ return create(block, draft => {
500
+ draft.statements = kept.map((statement, i) => i === 0 && kept[0] !== block.statements[0] ?
501
+ {...statement, element: {...statement.element, prefix: first}} : statement) as any;
502
+ });
503
+ }
504
+
479
505
  /**
480
506
  * Converts an Enzyme `mount` wrapper only when all of its uses can be converted together, so no
481
507
  * partially migrated wrapper can escape. Inline expressions such as
@@ -745,6 +771,243 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
745
771
  }
746
772
 
747
773
  override async visitBlock(block: J.Block, ctx: ExecutionContext): Promise<J | undefined> {
774
+ const shared = block.statements.map(statement => sharedWrapper(this.cursor, statement.element))
775
+ .filter((wrapper): wrapper is SharedWrapper => wrapper !== undefined);
776
+ if (shared.length === 0) return this.convertBlock(block, ctx);
777
+ const saved = this.saveState();
778
+ const original = this.cursor;
779
+ const {candidate, mounts} = await this.mountedInEachTest(block, shared, ctx);
780
+ this.cursor = new Cursor(candidate, original.parent);
781
+ const converted = await this.convertBlock(candidate, ctx);
782
+ this.cursor = original;
783
+ // Each test's wrapper converts, or the shared wrapper and every test keep Enzyme
784
+ if (mounts.every(id => this.mounts.has(id) && !this.pending.has(id))) return this.renderedInHooks(converted as J.Block, block, shared, ctx);
785
+ this.restoreState(saved);
786
+ return this.convertBlock(block, ctx);
787
+ }
788
+
789
+ /**
790
+ * The converted block with the renders each test of a describe starts with put back in the `beforeEach` they came
791
+ * from, where they are all the same, and the shared wrapper declared again for them. RTL renders in a hook as
792
+ * well, which keeps the tests as they were written, and its cleanup unmounts each render after its test.
793
+ */
794
+ private async renderedInHooks(block: J.Block, original: J.Block, shared: SharedWrapper[], ctx: ExecutionContext): Promise<J.Block> {
795
+ const groups = shared.flatMap(wrapper => wrapper.hooks.map(hook => ({wrapper, hook})));
796
+ if (groups.length === 0) return block;
797
+ const wanted = new Set(groups.flatMap(({hook}) => hook.tests));
798
+ const bodies = new Map<string, J.Block>();
799
+ await new class extends JavaScriptVisitor<ExecutionContext> {
800
+ override async visitBlock(inner: J.Block, p: ExecutionContext): Promise<J | undefined> {
801
+ if (wanted.has(inner.id)) bodies.set(inner.id, inner);
802
+ return super.visitBlock(inner, p);
803
+ }
804
+ }().visit(block, ctx, this.cursor.parent);
805
+ // NOTE: Prettier may lay out one test's render apart from the others', and quote it in its own style
806
+ const printer = TreePrinters.printer(JS.Kind.CompilationUnit);
807
+ const normalized = async (node: J) => (await printer.print(node)).replace(/\s+/g, "").replace(/"/g, "'");
808
+ const folds = new Map<string, {name: string, hook: SharedHook, render: Expression}>();
809
+ for (const {wrapper, hook} of groups) {
810
+ const firsts = hook.tests.map(id => bodies.get(id)?.statements[0]?.element);
811
+ if (firsts.length === 0 || firsts.some(first => first?.kind !== J.Kind.VariableDeclarations)) continue;
812
+ const renders = (firsts as J.VariableDeclarations[]).map(first => first.variables[0].element.initializer?.element);
813
+ if (renders.some(render => !render)) continue;
814
+ const printed = await Promise.all(renders.map(render => normalized(render!)));
815
+ if (printed.some(text => text !== printed[0])) continue;
816
+ folds.set(hook.owner, {name: wrapper.name, hook, render: renders[0]!});
817
+ }
818
+ if (folds.size === 0) return block;
819
+ const folded = new Set([...folds.values()].flatMap(({hook}) => hook.tests));
820
+ const declarations = shared.filter(wrapper => wrapper.hooks.some(hook => folds.has(hook.owner)))
821
+ .map(wrapper => wrapper.declaration);
822
+ const outer = this;
823
+ const visited = await new class extends JavaScriptVisitor<ExecutionContext> {
824
+ override async visitBlock(inner: J.Block, p: ExecutionContext): Promise<J | undefined> {
825
+ let visited = await super.visitBlock(inner, p) as J.Block;
826
+ if (folded.has(visited.id)) {
827
+ const [first, second, ...rest] = visited.statements;
828
+ return create(visited, draft => {
829
+ draft.statements = (second ? [{...second, element: {...second.element, prefix: first.element.prefix}}, ...rest] : []) as any;
830
+ });
831
+ }
832
+ const fold = folds.get(visited.id);
833
+ if (fold) visited = await outer.withHook(visited, fold, p);
834
+ if (visited.id === block.id) visited = await outer.withDeclarations(visited, original, declarations, p);
835
+ return visited;
836
+ }
837
+ }().visit<J.Block>(block, ctx, this.cursor.parent);
838
+ return visited!;
839
+ }
840
+
841
+ /** The describe with its `beforeEach` assigning the shared wrapper the render its tests started with. */
842
+ private async withHook(describe: J.Block, {hook, render}: {name: string, hook: SharedHook, render: Expression}, ctx: ExecutionContext): Promise<J.Block> {
843
+ const kept = describe.statements.find(statement => statement.element.id === hook.hook.id);
844
+ const statement = (kept?.element ?? hook.hook) as J;
845
+ const arrow = (expressionOf(statement) as J.MethodInvocation).arguments.elements[0].element as JS.ArrowFunction;
846
+ const body = arrow.lambda.body as J.Block;
847
+ const originalBody = ((expressionOf(hook.hook) as J.MethodInvocation).arguments.elements[0].element as JS.ArrowFunction).lambda.body as J.Block;
848
+ const mounting = originalBody.statements.find(padded => padded.element.id === hook.mounting)!;
849
+ // The render was converted from a copy of the hook's mount, so it keeps the hook's layout
850
+ const assigned = await withoutEnzymeTypes(create(mounting.element, (draft: any) => {
851
+ const assignment = draft.kind === JS.Kind.ExpressionStatement ? draft.expression : draft;
852
+ assignment.assignment.element = {...render, prefix: assignment.assignment.element.prefix};
853
+ assignment.type = undefined;
854
+ }), ctx);
855
+ const statements = [...body.statements.filter(padded => padded.element.id !== hook.mounting), {...mounting, element: assigned}];
856
+ const withBody = create(statement, (draft: any) => {
857
+ const target = draft.kind === JS.Kind.ExpressionStatement ? draft.expression : draft;
858
+ target.arguments.elements[0].element.lambda.body.statements = statements;
859
+ });
860
+ const statements2 = kept ? describe.statements.map(padded => padded === kept ? {...padded, element: withBody} : padded) :
861
+ inserted(describe.statements, hook.before, {...describe.statements[0], element: withBody});
862
+ return create(describe, draft => {
863
+ draft.statements = withPrefixes(statements2, hook.prefixes) as any;
864
+ });
865
+ }
866
+
867
+ /** The block with the shared wrappers declared again where they were, without their Enzyme types. */
868
+ private async withDeclarations(block: J.Block, original: J.Block, declarations: J.VariableDeclarations[], ctx: ExecutionContext): Promise<J.Block> {
869
+ let statements = [...block.statements];
870
+ const ids = original.statements.map(padded => padded.element.id);
871
+ for (const declaration of declarations) {
872
+ const padded = original.statements.find(statement => statement.element.id === declaration.id)!;
873
+ statements = inserted(statements, ids.slice(0, ids.indexOf(declaration.id)), {...padded, element: await this.renderResultDeclaration(declaration, original)});
874
+ }
875
+ const prefixes = new Map(original.statements.map(padded => [padded.element.id, padded.element.prefix] as const));
876
+ return create(block, draft => {
877
+ draft.statements = withPrefixes(statements, prefixes) as any;
878
+ });
879
+ }
880
+
881
+ /** The shared wrapper's declaration, typed as RTL's `RenderResult` where it had a type, which an Enzyme type was. */
882
+ private async renderResultDeclaration(declaration: J.VariableDeclarations, block: J.Block): Promise<J.VariableDeclarations> {
883
+ if (!declaration.typeExpression) return declaration;
884
+ const local = maybeAddImport(this, {module: RTL, member: "RenderResult", typeOnly: true, onlyIfReferenced: false}) ?? "RenderResult";
885
+ const name = (declaration.variables[0].element.name as J.Identifier).simpleName;
886
+ const typed = await Template.builder().code(`let ${name}: ${local}`).build()
887
+ .apply(declaration, new Cursor(declaration, new Cursor(block, this.cursor.parent))) as J.VariableDeclarations | undefined;
888
+ if (!typed) throw new Error(`Cannot declare ${name}`);
889
+ return {...typed, prefix: declaration.prefix};
890
+ }
891
+
892
+ /**
893
+ * The block with each test declaring the shared wrapper it mounts, without the shared declaration, its
894
+ * cleanup in `afterEach`, or the tests clearing it. An unmount that `afterEach` does before other statements
895
+ * becomes RTL's `cleanup()`, which keeps the order, and one after them is dropped, as RTL unmounts after them too.
896
+ */
897
+ private async mountedInEachTest(block: J.Block, shared: SharedWrapper[], ctx: ExecutionContext): Promise<{candidate: J.Block, mounts: string[]}> {
898
+ const names = new Map<string, string>();
899
+ shared.forEach(wrapper => wrapper.assignments.forEach(id => names.set(id, wrapper.name)));
900
+ const cleanup = new Set(shared.flatMap(wrapper => [...wrapper.cleanup]));
901
+ const unmounts = new Set(shared.flatMap(wrapper => [...wrapper.unmounts]));
902
+ const clears = new Set(shared.flatMap(wrapper => [...wrapper.clears, ...wrapper.hookRemovals]));
903
+ const hookMounts = new Map(shared.flatMap(wrapper => [...wrapper.hookMounts].map(([body, mount]) => [body, {name: wrapper.name, mount}] as const)));
904
+ const whole = (afterEach: J) => {
905
+ const body = (expressionOf(afterEach) as J.MethodInvocation).arguments.elements[0].element as JS.ArrowFunction;
906
+ const statements = body.lambda.body.kind === J.Kind.Block ? (body.lambda.body as J.Block).statements.map(s => s.element) : [body.lambda.body];
907
+ return statements.every(statement => cleanup.has(statement.id));
908
+ };
909
+ const removed = new Set(shared.flatMap(wrapper => [wrapper.declaration.id, ...wrapper.afterEach && whole(wrapper.afterEach) ? [wrapper.afterEach.id] : []]));
910
+ const trimmed = withoutStatements(block, removed);
911
+ const mounts: string[] = [];
912
+ const outer = this;
913
+ const candidate = await new class extends JavaScriptVisitor<ExecutionContext> {
914
+ override async visitBlock(inner: J.Block, p: ExecutionContext): Promise<J | undefined> {
915
+ const visited = await this.mountedFirst(await super.visitBlock(inner, p) as J.Block);
916
+ const own = (statement: J.Block["statements"][number]) => names.has(expressionOf(statement.element).id) ||
917
+ cleanup.has(statement.element.id) || clears.has(statement.element.id);
918
+ if (!visited.statements.some(own)) return visited;
919
+ const others = visited.statements.map(statement => cleanup.has(statement.element.id));
920
+ const last = others.lastIndexOf(false);
921
+ let cleaned = false;
922
+ const dropped = new Set<string>();
923
+ const statements: J.Block["statements"][number][] = [];
924
+ for (const [i, statement] of visited.statements.entries()) {
925
+ const id = statement.element.id;
926
+ const cursor = new Cursor(statement.element, new Cursor(visited, this.cursor.parent));
927
+ if (clears.has(id) || cleanup.has(id) && (cleaned || i > last || !unmounts.has(id))) {
928
+ dropped.add(id);
929
+ statements.push(statement);
930
+ continue;
931
+ }
932
+ if (cleanup.has(id)) {
933
+ const local = maybeAddImport(outer, {module: RTL, member: "cleanup", onlyIfReferenced: false}) ?? "cleanup";
934
+ const replaced = await Template.builder().code(`${local}()`).build().apply(statement.element, cursor) as J | undefined;
935
+ if (!replaced) throw new Error("Cannot clean up the shared wrapper");
936
+ cleaned = true;
937
+ // An `if` ends without a semicolon, which the call takes where the block's other statements have one
938
+ const semicolon = (padded: J.Block["statements"][number]) => padded.markers.markers.some(marker => marker.kind === J.Markers.Semicolon);
939
+ const markers = semicolon(statement) || !visited.statements.some(semicolon) ? statement.markers :
940
+ {...statement.markers, markers: [...statement.markers.markers, {kind: J.Markers.Semicolon, id: randomId()}]};
941
+ statements.push({...statement, markers, element: {...replaced, prefix: statement.element.prefix}});
942
+ continue;
943
+ }
944
+ const assignment = expressionOf(statement.element) as J.Assignment;
945
+ const name = names.get(assignment.id);
946
+ if (name === undefined) {
947
+ statements.push(statement);
948
+ continue;
949
+ }
950
+ const declare = Template.builder().code(`const ${name} = `).param(assignment.assignment.element).build();
951
+ const declared = await declare.apply(statement.element, cursor) as J.VariableDeclarations | undefined;
952
+ if (!declared) throw new Error(`Cannot declare ${name}`);
953
+ mounts.push(declared.variables[0].element.initializer!.element.id);
954
+ statements.push({...statement, element: {...declared, prefix: statement.element.prefix}});
955
+ }
956
+ return withoutStatements(create(visited, draft => {
957
+ draft.statements = statements as any;
958
+ }), dropped);
959
+ }
960
+
961
+ /** A test that its describe's `beforeEach` mounted the wrapper for, mounting it first itself. */
962
+ private async mountedFirst(test: J.Block): Promise<J.Block> {
963
+ const hooked = hookMounts.get(test.id);
964
+ if (!hooked) return test;
965
+ const [first, ...rest] = test.statements;
966
+ const cursor = new Cursor(first.element, new Cursor(test, this.cursor.parent));
967
+ // A copy for each test, whose ids the converter keeps apart
968
+ const declare = Template.builder().code(`const ${hooked.name} = `).param(withNewIds(hooked.mount)).build();
969
+ const declared = await declare.apply(first.element, cursor) as J.VariableDeclarations | undefined;
970
+ if (!declared) throw new Error(`Cannot declare ${hooked.name}`);
971
+ mounts.push(declared.variables[0].element.initializer!.element.id);
972
+ const semicolon = test.statements.some(padded => padded.markers.markers.some(marker => marker.kind === J.Markers.Semicolon));
973
+ const padded = {...first, element: {...declared, prefix: first.element.prefix},
974
+ markers: {...first.markers, markers: semicolon ? [{kind: J.Markers.Semicolon, id: randomId()}] : []}};
975
+ return create(test, draft => {
976
+ draft.statements = [padded, first, ...rest] as any;
977
+ });
978
+ }
979
+ }().visit<J.Block>(trimmed, ctx, this.cursor.parent);
980
+ return {candidate: candidate!, mounts};
981
+ }
982
+
983
+ private saveState() {
984
+ return {mounts: new Map(this.mounts), uses: new Map(this.uses), removedStatements: new Set(this.removedStatements),
985
+ unmounts: new Set(this.unmounts), declarations: new Set(this.declarations), pending: new Set(this.pending),
986
+ reformat: new Set(this.reformat), hoists: new Map(this.hoists), hoistedMounts: new Map(this.hoistedMounts),
987
+ portals: new Set(this.portals), rows: this.rows.length, afterVisit: this.afterVisit.length};
988
+ }
989
+
990
+ private restoreState(saved: ReturnType<typeof this.saveState>): void {
991
+ const refill = <T>(target: Set<T>, from: Set<T>) => {
992
+ target.clear();
993
+ from.forEach(value => target.add(value));
994
+ };
995
+ const remap = <K, V>(target: Map<K, V>, from: Map<K, V>) => {
996
+ target.clear();
997
+ from.forEach((value, key) => target.set(key, value));
998
+ };
999
+ remap(this.mounts, saved.mounts);
1000
+ remap(this.uses, saved.uses);
1001
+ remap(this.hoists, saved.hoists);
1002
+ remap(this.hoistedMounts, saved.hoistedMounts);
1003
+ [[this.removedStatements, saved.removedStatements], [this.unmounts, saved.unmounts], [this.declarations, saved.declarations],
1004
+ [this.pending, saved.pending], [this.reformat, saved.reformat], [this.portals, saved.portals]]
1005
+ .forEach(([target, from]) => refill(target, from));
1006
+ this.rows.length = saved.rows;
1007
+ this.afterVisit.length = saved.afterVisit;
1008
+ }
1009
+
1010
+ private async convertBlock(block: J.Block, ctx: ExecutionContext): Promise<J | undefined> {
748
1011
  const planned: string[] = [];
749
1012
  const apis: Render[] = [];
750
1013
  for (const statement of block.statements) {
@@ -43,17 +43,25 @@ export function enzymeWrapper(type: Type | undefined): boolean {
43
43
  name => /^enzyme\.(?:ReactWrapper|ShallowWrapper|CommonWrapper)$/.test(name));
44
44
  }
45
45
 
46
- export function migrationReason(api: string): {reason: string, suggestedAction: string} {
46
+ /** What an Enzyme `find`, `findWhere` or `filterWhere` matches by, which says how RTL queries the same elements. */
47
+ export type SelectorKind = "component" | "dom" | "enzyme" | "props" | "predicate";
48
+
49
+ /** What a `simulate` dispatches, which says what `fireEvent` needs to dispatch the same. */
50
+ export type EventKind = "event" | "hover" | "change" | "mock" | "other";
51
+
52
+ export function migrationReason(api: string, selector?: SelectorKind, event?: EventKind): {reason: string, suggestedAction: string} {
47
53
  if (api === "shallow" || api === "dive") {
48
54
  return {reason: "SHALLOW_RENDERING", suggestedAction: "Review child rendering and effects before replacing shallow rendering with RTL render."};
49
55
  }
50
56
  const internal = INTERNAL_STATE_ACTIONS[api];
51
57
  if (internal) return {reason: "INTERNAL_STATE", suggestedAction: internal};
52
58
  if (api === "simulate") {
53
- return {reason: "UNSUPPORTED_EVENT", suggestedAction: "Review event payloads and async control flow before selecting user-event or fireEvent."};
59
+ return {reason: "UNSUPPORTED_EVENT", suggestedAction: event && EVENT_ACTIONS[event] ||
60
+ "Review event payloads and async control flow before selecting user-event or fireEvent."};
54
61
  }
55
62
  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."};
63
+ return {reason: "SELECTOR_REVIEW", suggestedAction: selector && SELECTOR_ACTIONS[selector] ||
64
+ "Review selector scope, component versus DOM matching, and zero/one/multiple-match behavior."};
57
65
  }
58
66
  if (api === "mount") {
59
67
  return {reason: "RENDER_REVIEW", suggestedAction: "Review every use of the wrapper and its shared setup before replacing mount with RTL render."};
@@ -76,6 +84,22 @@ const INTERNAL_STATE_ACTIONS: Readonly<Record<string, string>> = {
76
84
  invoke: "Fire the DOM event that calls the handler, with `fireEvent` or `userEvent`, instead of invoking the prop."
77
85
  };
78
86
 
87
+ const SELECTOR_ACTIONS: Readonly<Record<SelectorKind, string>> = {
88
+ 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.",
89
+ 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.",
90
+ 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`.",
91
+ 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.",
92
+ 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."
93
+ };
94
+
95
+ const EVENT_ACTIONS: Readonly<Record<EventKind, string>> = {
96
+ 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.",
97
+ 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.",
98
+ 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.",
99
+ 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`.",
100
+ 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."
101
+ };
102
+
79
103
  const WRAPPER_API_ACTIONS: Readonly<Record<string, string>> = {
80
104
  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
105
  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.",