@openrewrite/recipes-react 0.14.0 → 0.15.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.
- package/dist/index.d.ts +12 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +70 -17
- package/dist/index.js.map +1 -1
- package/dist/migration/cra-to-vite/add-vite-config.d.ts +9 -0
- package/dist/migration/cra-to-vite/add-vite-config.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/add-vite-config.js +49 -0
- package/dist/migration/cra-to-vite/add-vite-config.js.map +1 -0
- package/dist/migration/cra-to-vite/cra-blockers-table.d.ts +10 -0
- package/dist/migration/cra-to-vite/cra-blockers-table.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-blockers-table.js +31 -0
- package/dist/migration/cra-to-vite/cra-blockers-table.js.map +1 -0
- package/dist/migration/cra-to-vite/cra-to-vite.d.ts +14 -0
- package/dist/migration/cra-to-vite/cra-to-vite.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-to-vite.js +73 -0
- package/dist/migration/cra-to-vite/cra-to-vite.js.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts +14 -0
- package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js +185 -0
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-env-file-blockers.d.ts +10 -0
- package/dist/migration/cra-to-vite/find-cra-env-file-blockers.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-env-file-blockers.js +67 -0
- package/dist/migration/cra-to-vite/find-cra-env-file-blockers.js.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-source-blockers.d.ts +10 -0
- package/dist/migration/cra-to-vite/find-cra-source-blockers.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-source-blockers.js +168 -0
- package/dist/migration/cra-to-vite/find-cra-source-blockers.js.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.d.ts +8 -0
- package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.js +31 -0
- package/dist/migration/cra-to-vite/find-cra-to-vite-blockers.js.map +1 -0
- package/dist/migration/cra-to-vite/index.d.ts +16 -0
- package/dist/migration/cra-to-vite/index.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/index.js +35 -0
- package/dist/migration/cra-to-vite/index.js.map +1 -0
- package/dist/migration/cra-to-vite/move-public-index-html.d.ts +11 -0
- package/dist/migration/cra-to-vite/move-public-index-html.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/move-public-index-html.js +124 -0
- package/dist/migration/cra-to-vite/move-public-index-html.js.map +1 -0
- package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts +9 -0
- package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/rename-process-env-react-app.js +92 -0
- package/dist/migration/cra-to-vite/rename-process-env-react-app.js.map +1 -0
- package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.d.ts +9 -0
- package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js +65 -0
- package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js.map +1 -0
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts +14 -0
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js +98 -0
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js.map +1 -0
- package/dist/migration/cra-to-vite/scan-cra-projects.d.ts +21 -0
- package/dist/migration/cra-to-vite/scan-cra-projects.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/scan-cra-projects.js +87 -0
- package/dist/migration/cra-to-vite/scan-cra-projects.js.map +1 -0
- package/dist/migration/cra-to-vite/shared.d.ts +37 -0
- package/dist/migration/cra-to-vite/shared.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/shared.js +218 -0
- package/dist/migration/cra-to-vite/shared.js.map +1 -0
- package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts +9 -0
- package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/update-react-app-env-types.js +47 -0
- package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -0
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts +9 -0
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.js +67 -0
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -0
- package/dist/migration/cra-to-vite/update-tsconfig-for-vite.d.ts +10 -0
- package/dist/migration/cra-to-vite/update-tsconfig-for-vite.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js +53 -0
- package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js.map +1 -0
- package/dist/react17/migrate-deprecated-lifecycles.d.ts +8 -0
- package/dist/react17/migrate-deprecated-lifecycles.d.ts.map +1 -0
- package/dist/react17/migrate-deprecated-lifecycles.js +258 -0
- package/dist/react17/migrate-deprecated-lifecycles.js.map +1 -0
- package/dist/react17/use-new-jsx-transform.d.ts +8 -0
- package/dist/react17/use-new-jsx-transform.d.ts.map +1 -0
- package/dist/react17/use-new-jsx-transform.js +169 -0
- package/dist/react17/use-new-jsx-transform.js.map +1 -0
- package/dist/react18/add-children-to-props.d.ts +8 -0
- package/dist/react18/add-children-to-props.d.ts.map +1 -0
- package/dist/react18/add-children-to-props.js +277 -0
- package/dist/react18/add-children-to-props.js.map +1 -0
- package/dist/react18/replace-reactdom-render.d.ts.map +1 -1
- package/dist/react18/replace-reactdom-render.js +109 -12
- package/dist/react18/replace-reactdom-render.js.map +1 -1
- package/dist/refactoring/class-to-functional.d.ts.map +1 -1
- package/dist/refactoring/class-to-functional.js +81 -7
- package/dist/refactoring/class-to-functional.js.map +1 -1
- package/dist/refactoring/fix-async-effect.d.ts +8 -0
- package/dist/refactoring/fix-async-effect.d.ts.map +1 -0
- package/dist/refactoring/fix-async-effect.js +71 -0
- package/dist/refactoring/fix-async-effect.js.map +1 -0
- package/dist/refactoring/prop-types-to-typescript.d.ts +8 -0
- package/dist/refactoring/prop-types-to-typescript.d.ts.map +1 -0
- package/dist/refactoring/prop-types-to-typescript.js +342 -0
- package/dist/refactoring/prop-types-to-typescript.js.map +1 -0
- package/dist/search/find-deprecated-lifecycles.d.ts +12 -0
- package/dist/search/find-deprecated-lifecycles.d.ts.map +1 -0
- package/dist/search/find-deprecated-lifecycles.js +86 -0
- package/dist/search/find-deprecated-lifecycles.js.map +1 -0
- package/dist/search/find-effects-without-cleanup.d.ts +9 -0
- package/dist/search/find-effects-without-cleanup.d.ts.map +1 -0
- package/dist/search/find-effects-without-cleanup.js +133 -0
- package/dist/search/find-effects-without-cleanup.js.map +1 -0
- package/dist/search/find-enzyme-usage.d.ts +9 -0
- package/dist/search/find-enzyme-usage.d.ts.map +1 -0
- package/dist/search/find-enzyme-usage.js +155 -0
- package/dist/search/find-enzyme-usage.js.map +1 -0
- package/dist/search/find-function-component-default-props.d.ts +11 -0
- package/dist/search/find-function-component-default-props.d.ts.map +1 -0
- package/dist/search/find-function-component-default-props.js +96 -0
- package/dist/search/find-function-component-default-props.js.map +1 -0
- package/dist/search/find-legacy-react-apis.d.ts +8 -0
- package/dist/search/find-legacy-react-apis.d.ts.map +1 -0
- package/dist/search/find-legacy-react-apis.js +41 -0
- package/dist/search/find-legacy-react-apis.js.map +1 -0
- package/dist/search/find-missing-use-client-directive.d.ts +9 -0
- package/dist/search/find-missing-use-client-directive.d.ts.map +1 -0
- package/dist/search/find-missing-use-client-directive.js +127 -0
- package/dist/search/find-missing-use-client-directive.js.map +1 -0
- package/dist/search/find-reactdom-root-apis.d.ts +14 -0
- package/dist/search/find-reactdom-root-apis.d.ts.map +1 -0
- package/dist/search/find-reactdom-root-apis.js +122 -0
- package/dist/search/find-reactdom-root-apis.js.map +1 -0
- package/dist/testing/enzyme-to-react-testing-library.d.ts +36 -0
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -0
- package/dist/testing/enzyme-to-react-testing-library.js +547 -0
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -0
- package/dist/testing/enzyme-usage.d.ts +22 -0
- package/dist/testing/enzyme-usage.d.ts.map +1 -0
- package/dist/testing/enzyme-usage.js +107 -0
- package/dist/testing/enzyme-usage.js.map +1 -0
- package/dist/testing/enzyme-wrapper-scope.d.ts +42 -0
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -0
- package/dist/testing/enzyme-wrapper-scope.js +422 -0
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -0
- package/dist/util/react-class.d.ts +6 -0
- package/dist/util/react-class.d.ts.map +1 -0
- package/dist/util/react-class.js +41 -0
- package/dist/util/react-class.js.map +1 -0
- package/dist/util/tree-search.d.ts +6 -0
- package/dist/util/tree-search.d.ts.map +1 -0
- package/dist/util/tree-search.js +51 -0
- package/dist/util/tree-search.js.map +1 -0
- package/package.json +7 -4
- package/src/index.ts +53 -12
- package/src/migration/cra-to-vite/add-vite-config.ts +47 -0
- package/src/migration/cra-to-vite/cra-blockers-table.ts +27 -0
- package/src/migration/cra-to-vite/cra-to-vite.ts +76 -0
- package/src/migration/cra-to-vite/find-cra-config-blockers.ts +179 -0
- package/src/migration/cra-to-vite/find-cra-env-file-blockers.ts +60 -0
- package/src/migration/cra-to-vite/find-cra-source-blockers.ts +138 -0
- package/src/migration/cra-to-vite/find-cra-to-vite-blockers.ts +21 -0
- package/src/migration/cra-to-vite/index.ts +26 -0
- package/src/migration/cra-to-vite/move-public-index-html.ts +132 -0
- package/src/migration/cra-to-vite/rename-process-env-react-app.ts +93 -0
- package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +61 -0
- package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +96 -0
- package/src/migration/cra-to-vite/scan-cra-projects.ts +86 -0
- package/src/migration/cra-to-vite/shared.ts +244 -0
- package/src/migration/cra-to-vite/update-react-app-env-types.ts +40 -0
- package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +69 -0
- package/src/migration/cra-to-vite/update-tsconfig-for-vite.ts +47 -0
- package/src/react17/migrate-deprecated-lifecycles.ts +265 -0
- package/src/react17/use-new-jsx-transform.ts +150 -0
- package/src/react18/add-children-to-props.ts +235 -0
- package/src/react18/replace-reactdom-render.ts +109 -20
- package/src/refactoring/class-to-functional.ts +101 -13
- package/src/refactoring/fix-async-effect.ts +88 -0
- package/src/refactoring/prop-types-to-typescript.ts +341 -0
- package/src/search/find-deprecated-lifecycles.ts +64 -0
- package/src/search/find-effects-without-cleanup.ts +109 -0
- package/src/search/find-enzyme-usage.ts +117 -0
- package/src/search/find-function-component-default-props.ts +68 -0
- package/src/search/find-legacy-react-apis.ts +41 -0
- package/src/search/find-missing-use-client-directive.ts +99 -0
- package/src/search/find-reactdom-root-apis.ts +99 -0
- package/src/testing/enzyme-to-react-testing-library.ts +553 -0
- package/src/testing/enzyme-usage.ts +94 -0
- package/src/testing/enzyme-wrapper-scope.ts +449 -0
- package/src/util/react-class.ts +34 -0
- package/src/util/tree-search.ts +32 -0
- package/dist/react16/upgrade-to-react-16.d.ts +0 -12
- package/dist/react16/upgrade-to-react-16.d.ts.map +0 -1
- package/dist/react16/upgrade-to-react-16.js +0 -66
- package/dist/react16/upgrade-to-react-16.js.map +0 -1
- package/dist/react17/upgrade-to-react-17.d.ts +0 -12
- package/dist/react17/upgrade-to-react-17.d.ts.map +0 -1
- package/dist/react17/upgrade-to-react-17.js +0 -62
- package/dist/react17/upgrade-to-react-17.js.map +0 -1
- package/dist/react18/upgrade-to-react-18.d.ts +0 -12
- package/dist/react18/upgrade-to-react-18.d.ts.map +0 -1
- package/dist/react18/upgrade-to-react-18.js +0 -64
- package/dist/react18/upgrade-to-react-18.js.map +0 -1
- package/dist/react19/upgrade-to-react-19.d.ts +0 -8
- package/dist/react19/upgrade-to-react-19.d.ts.map +0 -1
- package/dist/react19/upgrade-to-react-19.js +0 -68
- package/dist/react19/upgrade-to-react-19.js.map +0 -1
- package/src/react16/upgrade-to-react-16.ts +0 -59
- package/src/react17/upgrade-to-react-17.ts +0 -52
- package/src/react18/upgrade-to-react-18.ts +0 -55
- package/src/react19/upgrade-to-react-19.ts +0 -75
|
@@ -0,0 +1,553 @@
|
|
|
1
|
+
import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, ScanningRecipe, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
import {addDependency, AddDependencyOptions, autoFormat, capture, PrettierStyle, deconflict, findNodeResolutionResult, isVendoredOrBundled, JavaScriptVisitor, JS, maybeRemoveImport, moduleBindings, namesUsedIn, pattern, rewrite, StyleKind, Template, template, usesMethod} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {Expression, J} from "@openrewrite/rewrite/java";
|
|
4
|
+
import {create} from "mutative";
|
|
5
|
+
import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
|
|
6
|
+
import {readFileSync} from "fs";
|
|
7
|
+
import {dirname, join} from "path";
|
|
8
|
+
import {satisfies, validRange} from "semver";
|
|
9
|
+
import {FindEnzymeUsage} from "../search/find-enzyme-usage";
|
|
10
|
+
import {ENZYME, ENZYME_USAGE_TABLE, enclosingScope, EnzymeUsageRow} from "./enzyme-usage";
|
|
11
|
+
import {analyzeWrapperScope, idsWithin, mountedElement, selectorLiteral, simpleChain, statementPosition, withoutEnzymeTypes, withRenderOptionsOnElementLine, wrapperDeclaration, WrapperRead} from "./enzyme-wrapper-scope";
|
|
12
|
+
|
|
13
|
+
const RTL = "@testing-library/react";
|
|
14
|
+
|
|
15
|
+
const REACT_RANGE = ">=16.9.0 <18";
|
|
16
|
+
|
|
17
|
+
/** RTL 12 supports React 16.9 to 17, so it goes where Enzyme is used with those. */
|
|
18
|
+
const RTL_ADDITION: AddDependencyOptions = {
|
|
19
|
+
packageName: RTL, version: "^12.1.5", scope: "devDependencies",
|
|
20
|
+
onlyIfDeclaring: ["enzyme"], onlyIfResolving: [`react@${REACT_RANGE}`, `react-dom@${REACT_RANGE}`]
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Older hosts drop the `onlyIfResolving` option they do not know, which would add RTL to every
|
|
25
|
+
* package declaring Enzyme, so RTL is only added where the host has it.
|
|
26
|
+
*/
|
|
27
|
+
const ADDS_RTL = (() => {
|
|
28
|
+
try {
|
|
29
|
+
return supportsResolvingGate(rewriteVersion(require.resolve("@openrewrite/rewrite"), require.cache));
|
|
30
|
+
} catch {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
})();
|
|
34
|
+
|
|
35
|
+
export function supportsResolvingGate(version: string | undefined): boolean {
|
|
36
|
+
const match = /^(\d+)\.(\d+)\.(\d+)(-)?/.exec(version ?? "");
|
|
37
|
+
if (!match) return false;
|
|
38
|
+
const [major, minor, patch] = match.slice(1, 4).map(Number);
|
|
39
|
+
const order = major - 8 || minor - 97 || patch - 2;
|
|
40
|
+
return order > 0 || order === 0 && !match[4];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The version of the `@openrewrite/rewrite` package that `resolved` runs as. A host sharing its own
|
|
45
|
+
* copy with a recipe package maps the package's module paths to the host's modules in the require
|
|
46
|
+
* cache, so the module's own file name says which copy that is.
|
|
47
|
+
*/
|
|
48
|
+
export function rewriteVersion(resolved: string, cache: Record<string, {filename: string} | undefined>): string | undefined {
|
|
49
|
+
for (let dir = dirname(cache[resolved]?.filename ?? resolved); dirname(dir) !== dir; dir = dirname(dir)) {
|
|
50
|
+
try {
|
|
51
|
+
const manifest = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
|
|
52
|
+
if (manifest.name === "@openrewrite/rewrite") return manifest.version;
|
|
53
|
+
} catch {
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A wrapper's rendered element, declared ahead of the wrapper for `setProps` to clone. */
|
|
61
|
+
interface HoistedElement {
|
|
62
|
+
name: string;
|
|
63
|
+
element: J;
|
|
64
|
+
reassigned: boolean;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** A declared version within one major, with its minor version where the declaration fixes one. */
|
|
68
|
+
interface DeclaredVersion {
|
|
69
|
+
major: number;
|
|
70
|
+
minor?: number;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** A package's declaration of each dependency the migration needs: absent, unsupported, or within a major. */
|
|
74
|
+
type Declaration = DeclaredVersion | "unsupported" | undefined;
|
|
75
|
+
|
|
76
|
+
interface PackageDeclarations {
|
|
77
|
+
react: Declaration;
|
|
78
|
+
reactDom: Declaration;
|
|
79
|
+
rtl: Declaration;
|
|
80
|
+
enzyme: boolean;
|
|
81
|
+
/**
|
|
82
|
+
* `addDependency` leaves a package unchanged when it cannot regenerate its lockfile, as for pnpm
|
|
83
|
+
* versions it does not reproduce, so only npm and Yarn packages are counted on to receive RTL.
|
|
84
|
+
*/
|
|
85
|
+
lockfileRegenerated: boolean;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Package roots, such as `packages/ui/`, mapped to their declarations. */
|
|
89
|
+
type Packages = Map<string, PackageDeclarations>;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The React major version the tests of a source file run with, or 0 where they cannot migrate. A
|
|
93
|
+
* dependency the owning package does not declare comes from the nearest enclosing package that
|
|
94
|
+
* does, where Node resolves it from. Where the run adds RTL, as {@link RTL_ADDITION} does, it is
|
|
95
|
+
* there for every package within the nearest package declaring Enzyme.
|
|
96
|
+
*/
|
|
97
|
+
export function reactMajor(packages: Packages, sourcePath: string, addsRtl = false): number {
|
|
98
|
+
return compatibility(packages, sourcePath, addsRtl).react;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Whether `simulate` can become `fireEvent` for a source file: on React 17, with an RTL whose
|
|
103
|
+
* `fireEvent.focus`, `blur`, `mouseEnter`, and `mouseLeave` also dispatch the events React 17
|
|
104
|
+
* listens to, which RTL 10 does only from 10.4.9.
|
|
105
|
+
*/
|
|
106
|
+
export function simulatesEvents(packages: Packages, sourcePath: string, addsRtl = false): boolean {
|
|
107
|
+
const {react, rtl} = compatibility(packages, sourcePath, addsRtl);
|
|
108
|
+
return react === 17 && rtl >= 11;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The React major as {@link reactMajor} reads it, and the major of the RTL the tests run with. */
|
|
112
|
+
function compatibility(packages: Packages, sourcePath: string, addsRtl: boolean): {react: number, rtl: number} {
|
|
113
|
+
const roots = [...packages.keys()].filter(root => sourcePath.startsWith(root)).sort((a, b) => b.length - a.length);
|
|
114
|
+
const declared = (name: "react" | "reactDom" | "rtl", from = roots) =>
|
|
115
|
+
from.map(root => packages.get(root)![name]).find(version => version !== undefined);
|
|
116
|
+
const supportedReact = (version: Declaration): version is DeclaredVersion => typeof version === "object" &&
|
|
117
|
+
(version.major === 17 || (version.major === 16 && version.minor !== undefined && version.minor >= 9));
|
|
118
|
+
const react = declared("react");
|
|
119
|
+
const rtl = declared("rtl");
|
|
120
|
+
const enzyme = roots.findIndex(root => packages.get(root)!.enzyme);
|
|
121
|
+
const added = addsRtl && rtl === undefined && enzyme >= 0 && packages.get(roots[enzyme])!.lockfileRegenerated &&
|
|
122
|
+
supportedReact(declared("react", roots.slice(enzyme))) && supportedReact(declared("reactDom", roots.slice(enzyme)));
|
|
123
|
+
// RTL renders with the React DOM it resolves from its own package
|
|
124
|
+
const rtlRoot = added ? enzyme : roots.findIndex(root => packages.get(root)!.rtl !== undefined);
|
|
125
|
+
const reactDom = declared("reactDom", roots.slice(Math.max(rtlRoot, 0))) ?? declared("reactDom");
|
|
126
|
+
// `render` with a container, `rerender`, `unmount`, and `fireEvent` are all there since RTL 10
|
|
127
|
+
const rtlMajor = added ? 12 : typeof rtl === "object" && rtl.major >= 10 && rtl.major <= 12 ? rtl.major : 0;
|
|
128
|
+
const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major && rtlMajor > 0;
|
|
129
|
+
return {react: compatible ? react.major : 0, rtl: rtlMajor};
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* A version or a range within a single major: `16.14.0`, `^16.14`, `~16.9.0`, `16.9.x`, or `^17`,
|
|
134
|
+
* whose minor version is known only where it is a lower bound.
|
|
135
|
+
*/
|
|
136
|
+
function declaredVersion(version: string | undefined): Declaration {
|
|
137
|
+
if (version === undefined) return undefined;
|
|
138
|
+
const match = /^([\^~]?)(\d+)(?:\.(\d+|x|\*)(?:\.(\d+|x|\*))?)?$/.exec(version.trim());
|
|
139
|
+
if (!match) return "unsupported";
|
|
140
|
+
return {major: Number(match[2]), minor: /^\d+$/.test(match[3] ?? "") ? Number(match[3]) : undefined};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Converts an Enzyme `mount` wrapper only when all of its uses can be converted together, so no
|
|
145
|
+
* partially migrated wrapper can escape. Inline expressions such as
|
|
146
|
+
* `mount(<Button />).find('button').length` and `const wrapper = mount(<Button />)` declarations
|
|
147
|
+
* whose every reference is a supported DOM read become RTL renders into a detached container.
|
|
148
|
+
*
|
|
149
|
+
* Existing compatible RTL installation and DOM test setup are prerequisites. More complex
|
|
150
|
+
* wrapper flows remain in the inventory rather than being guessed at.
|
|
151
|
+
*
|
|
152
|
+
* @see https://testing-library.com/docs/react-testing-library/migrate-from-enzyme/#how-to-migrate-from-enzyme-to-react-testing-library
|
|
153
|
+
*/
|
|
154
|
+
export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
155
|
+
readonly name = "org.openrewrite.react.migrate.enzyme-to-react-testing-library";
|
|
156
|
+
readonly displayName = "Migrate Enzyme to React Testing Library";
|
|
157
|
+
readonly description = "Migrates Enzyme `mount` wrappers whose every use is a supported DOM read or event (`find(selector).length`, `.exists()`, `.text()`, `.html()`, `.hasClass()`, positions through `.at(n)`, `.first()`, `.last()`, the wrapper's `text()` and `exists(selector)`, found nodes as a `toHaveLength` subject, `setProps` as a rerender of the cloned element, and on React 17 `simulate` with common mouse, keyboard, focus, form, and touch events, including `nativeEvent` mocks) and bare `mount` statements to React Testing Library container queries, `rerender`, and `fireEvent` in packages using React 16.9+/17 with RTL 10 to 12, adding RTL 12 where it is missing. Selectors are limited to HTML or SVG tag, class, ID, and pass-through attribute compounds and their descendant combinations. Reports remaining Enzyme usages for manual review. Requires an existing DOM test environment; shared wrappers, props, and snapshots are left for review.";
|
|
158
|
+
|
|
159
|
+
@Option({
|
|
160
|
+
displayName: "Convert positions into untagged selector matches",
|
|
161
|
+
description: "Whether a position into the matches of a selector with a compound that names no tag, such as `find('.slice').at(1)`, is converted. Enzyme also matches a component that receives the class, ID, or attribute as a prop, which shifts the positions of the elements after it; converting assumes that no component in the rendered tree receives it. Defaults to `true`; set it to `false` to convert only positions into tag-qualified matches.",
|
|
162
|
+
required: false
|
|
163
|
+
})
|
|
164
|
+
untaggedSelectorPositions?: boolean;
|
|
165
|
+
|
|
166
|
+
constructor(options?: {untaggedSelectorPositions?: boolean}) {
|
|
167
|
+
super(options);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
private readonly usages = new DataTable<EnzymeUsageRow>(
|
|
171
|
+
ENZYME_USAGE_TABLE, "Enzyme migration inventory",
|
|
172
|
+
"Remaining Enzyme usages and migration actions. Module rows include references whose call types may be unavailable; they are not counts of test cases.",
|
|
173
|
+
EnzymeUsageRow
|
|
174
|
+
);
|
|
175
|
+
|
|
176
|
+
initialValue(): Packages {
|
|
177
|
+
return new Map();
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async scanner(packages: Packages): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
181
|
+
return new class extends JsonVisitor<ExecutionContext> {
|
|
182
|
+
override async visitDocument(doc: Json.Document, ctx: ExecutionContext): Promise<Json | undefined> {
|
|
183
|
+
if (!/(^|\/)package\.json$/.test(doc.sourcePath)) return doc;
|
|
184
|
+
const resolution = findNodeResolutionResult(doc);
|
|
185
|
+
// In the order the dependency gate of `addDependency` reads them
|
|
186
|
+
const dependencies = [...resolution?.dependencies ?? [], ...resolution?.devDependencies ?? [],
|
|
187
|
+
...resolution?.optionalDependencies ?? [], ...resolution?.peerDependencies ?? []];
|
|
188
|
+
// The lockfile's resolved version is what the tests run against, unless it is outside the
|
|
189
|
+
// declared semver range, as a hoisted Yarn workspace resolution can be. Without one, accept only
|
|
190
|
+
// ranges within a single major; catalogs, aliases, and cross-major ranges stay unsupported.
|
|
191
|
+
const version = (name: string) => {
|
|
192
|
+
const dependency = dependencies.find(dep => dep.name === name && dep.resolved);
|
|
193
|
+
const resolved = dependency?.resolved;
|
|
194
|
+
if (resolved?.name === name && /^\d+\.\d+\.\d+$/.test(resolved.version) &&
|
|
195
|
+
(!validRange(dependency!.versionConstraint) || satisfies(resolved.version, dependency!.versionConstraint))) return resolved.version;
|
|
196
|
+
return dependencies.find(dep => dep.name === name)?.versionConstraint;
|
|
197
|
+
};
|
|
198
|
+
packages.set(doc.sourcePath.slice(0, -"package.json".length), {
|
|
199
|
+
react: declaredVersion(version("react")),
|
|
200
|
+
reactDom: declaredVersion(version("react-dom")),
|
|
201
|
+
rtl: declaredVersion(version(RTL)),
|
|
202
|
+
enzyme: dependencies.some(dep => dep.name === "enzyme"),
|
|
203
|
+
lockfileRegenerated: resolution?.packageManager !== "Pnpm" && resolution?.packageManager !== "Bun"
|
|
204
|
+
});
|
|
205
|
+
return doc;
|
|
206
|
+
}
|
|
207
|
+
}();
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async editorWithData(packages: Packages): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
211
|
+
const jsx = capture<Expression>({name: "element", constraint: node => node.kind !== JS.Kind.Spread});
|
|
212
|
+
const selector = capture<J.Literal>({name: "selector", constraint: node => selectorLiteral(node)});
|
|
213
|
+
const before = {lenientTypeMatching: false, context: ['import {mount} from "enzyme";'], dependencies: {"@types/enzyme": "3.10.19", "@types/react": "16.14.62"}};
|
|
214
|
+
const after = {context: [`import {render} from "${RTL}";`], dependencies: {[RTL]: "12.1.5", "@types/react": "16.14.62"}};
|
|
215
|
+
const lengthRule = rewrite(() => ({
|
|
216
|
+
before: pattern`mount(${jsx}).find(${selector}).length`.configure(before),
|
|
217
|
+
after: template`render(${jsx}, {container: globalThis.document.createElement('div')}).container.querySelectorAll(${selector}).length`.configure(after)
|
|
218
|
+
}));
|
|
219
|
+
const existsRule = rewrite(() => ({
|
|
220
|
+
before: pattern`mount(${jsx}).find(${selector}).exists()`.configure(before),
|
|
221
|
+
after: template`(render(${jsx}, {container: globalThis.document.createElement('div')}).container.querySelectorAll(${selector}).length > 0)`.configure(after)
|
|
222
|
+
}));
|
|
223
|
+
const existsArgumentRule = rewrite(() => ({
|
|
224
|
+
before: pattern`mount(${jsx}).find(${selector}).exists()`.configure(before),
|
|
225
|
+
after: template`render(${jsx}, {container: globalThis.document.createElement('div')}).container.querySelectorAll(${selector}).length > 0`.configure(after)
|
|
226
|
+
}));
|
|
227
|
+
const mountPattern = pattern`mount(${jsx})`.configure(before);
|
|
228
|
+
const mountRule = rewrite(() => ({
|
|
229
|
+
before: mountPattern,
|
|
230
|
+
after: template`render(${jsx}, {container: globalThis.document.createElement('div')})`.configure(after)
|
|
231
|
+
}));
|
|
232
|
+
const usages = this.usages;
|
|
233
|
+
const untaggedPositions = this.untaggedSelectorPositions !== false;
|
|
234
|
+
return check(and(not(isVendoredOrBundled()), usesMethod("enzyme mount(..)")), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
235
|
+
private enabled = false;
|
|
236
|
+
private reactMajor = 0;
|
|
237
|
+
private events = false;
|
|
238
|
+
private typescript = false;
|
|
239
|
+
private sourcePath = "";
|
|
240
|
+
private readonly mounts = new Set<string>();
|
|
241
|
+
private readonly uses = new Map<string, WrapperRead>();
|
|
242
|
+
private readonly removedStatements = new Set<string>();
|
|
243
|
+
private readonly unmounts = new Set<string>();
|
|
244
|
+
private readonly declarations = new Set<string>();
|
|
245
|
+
private readonly pending = new Set<string>();
|
|
246
|
+
private readonly reformat = new Set<string>();
|
|
247
|
+
private readonly hoists = new Map<string, HoistedElement>();
|
|
248
|
+
private readonly hoistedMounts = new Map<string, string>();
|
|
249
|
+
private names: ReadonlySet<string> = new Set();
|
|
250
|
+
private readonly rows: EnzymeUsageRow[] = [];
|
|
251
|
+
private prettier = false;
|
|
252
|
+
private printWidth = 80;
|
|
253
|
+
|
|
254
|
+
override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
255
|
+
this.sourcePath = cu.sourcePath;
|
|
256
|
+
[this.mounts, this.uses, this.removedStatements, this.unmounts, this.declarations, this.pending, this.reformat].forEach(ids => ids.clear());
|
|
257
|
+
this.hoists.clear();
|
|
258
|
+
this.hoistedMounts.clear();
|
|
259
|
+
this.rows.length = 0;
|
|
260
|
+
this.names = namesUsedIn(cu);
|
|
261
|
+
const prettierStyle = findMarker<PrettierStyle>(cu, StyleKind.PrettierStyle);
|
|
262
|
+
this.prettier = prettierStyle !== undefined;
|
|
263
|
+
this.printWidth = typeof prettierStyle?.config.printWidth === "number" ? prettierStyle.config.printWidth : 80;
|
|
264
|
+
this.reactMajor = reactMajor(packages, cu.sourcePath, ADDS_RTL);
|
|
265
|
+
this.events = simulatesEvents(packages, cu.sourcePath, ADDS_RTL);
|
|
266
|
+
this.typescript = /\.[cm]?tsx?$/.test(cu.sourcePath);
|
|
267
|
+
this.enabled = this.reactMajor > 0 && moduleBindings(this).moduleSystem === "esm";
|
|
268
|
+
if (!this.enabled || this.names.has("globalThis")) return cu;
|
|
269
|
+
const visited = await super.visitJsCompilationUnit(cu, ctx);
|
|
270
|
+
this.rows.forEach(row => usages.insertRow(ctx, row));
|
|
271
|
+
return visited;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
override async visitBlock(block: J.Block, ctx: ExecutionContext): Promise<J | undefined> {
|
|
275
|
+
const planned: string[] = [];
|
|
276
|
+
let scopes = 0;
|
|
277
|
+
for (const statement of block.statements) {
|
|
278
|
+
const candidate = wrapperDeclaration(statement.element);
|
|
279
|
+
if (!candidate) continue;
|
|
280
|
+
const scope = await analyzeWrapperScope(block, candidate.declaration, candidate.name, this.events, untaggedPositions, this.cursor.parent!, ctx);
|
|
281
|
+
if (!scope || !await this.mountMatches(candidate.mount.id, block, ctx)) continue;
|
|
282
|
+
this.mounts.add(candidate.mount.id);
|
|
283
|
+
this.declarations.add(candidate.declaration.id);
|
|
284
|
+
scope.uses.forEach((use, id) => this.uses.set(id, use));
|
|
285
|
+
scope.removedStatements.forEach(id => this.removedStatements.add(id));
|
|
286
|
+
scope.unmounts.forEach(id => this.unmounts.add(id));
|
|
287
|
+
const setProps = [...scope.uses.values()].filter(read => read.use === "setProps");
|
|
288
|
+
if (setProps.length > 0) {
|
|
289
|
+
const name = deconflict(`${candidate.name}Element`, name => this.names.has(name));
|
|
290
|
+
const reassigned = setProps.length > 1;
|
|
291
|
+
setProps.forEach(read => Object.assign(read, {element: name, reassigned}));
|
|
292
|
+
this.hoists.set(candidate.declaration.id, {name, element: candidate.mount.arguments.elements[0].element, reassigned});
|
|
293
|
+
this.hoistedMounts.set(candidate.mount.id, name);
|
|
294
|
+
}
|
|
295
|
+
planned.push(candidate.mount.id, ...scope.uses.keys());
|
|
296
|
+
scopes++;
|
|
297
|
+
}
|
|
298
|
+
planned.forEach(id => this.pending.add(id));
|
|
299
|
+
const queued = this.afterVisit.length;
|
|
300
|
+
const rows = this.rows.length;
|
|
301
|
+
const visited = await super.visitBlock(block, ctx) as J.Block;
|
|
302
|
+
// Every use was matched before planning, so this only guards against a template
|
|
303
|
+
// failing to apply: never leave a wrapper half converted.
|
|
304
|
+
if (planned.some(id => this.pending.has(id))) {
|
|
305
|
+
this.afterVisit.length = queued;
|
|
306
|
+
this.rows.length = rows;
|
|
307
|
+
(await idsWithin(block, this.reformat, ctx)).forEach(id => this.reformat.delete(id));
|
|
308
|
+
// Uses of a wrapper declared further out are rolled back too, which its block has to see
|
|
309
|
+
(await idsWithin(block, new Set([...this.mounts, ...this.uses.keys()]), ctx)).forEach(id => this.pending.add(id));
|
|
310
|
+
return block;
|
|
311
|
+
}
|
|
312
|
+
for (let i = 0; i < scopes; i++) this.converted("mount", enclosingScope(this.cursor), "WRAPPER_SCOPE");
|
|
313
|
+
// Prettier lays out statements by their position in the block as it was parsed, before any is added or removed
|
|
314
|
+
const laidOut = await this.withPrettierLayout(visited, ctx);
|
|
315
|
+
const statements: J.Block["statements"][number][] = [];
|
|
316
|
+
for (const statement of laidOut.statements) {
|
|
317
|
+
const element = statement.element as J;
|
|
318
|
+
const expression = element.kind === JS.Kind.ExpressionStatement ? (element as JS.ExpressionStatement).expression : element;
|
|
319
|
+
if (this.removedStatements.has(expression.id)) continue;
|
|
320
|
+
const hoist = this.hoists.get(element.id);
|
|
321
|
+
if (hoist) statements.push(...await this.withHoistedElement(hoist, statement, laidOut));
|
|
322
|
+
else statements.push(statement);
|
|
323
|
+
}
|
|
324
|
+
if (statements.length === laidOut.statements.length && statements.every((statement, i) => statement === laidOut.statements[i])) return laidOut;
|
|
325
|
+
return create(laidOut, draft => {
|
|
326
|
+
draft.statements = statements as any;
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** Declares the element ahead of the wrapper, which keeps any comments only on the first. */
|
|
331
|
+
private async withHoistedElement(hoist: HoistedElement, statement: J.Block["statements"][number],
|
|
332
|
+
block: J.Block): Promise<J.Block["statements"][number][]> {
|
|
333
|
+
const declaration = statement.element;
|
|
334
|
+
const prefix = declaration.prefix;
|
|
335
|
+
const indent = prefix.comments.length > 0 ? prefix.comments[prefix.comments.length - 1].suffix : prefix.whitespace;
|
|
336
|
+
const declarator = `${hoist.reassigned ? "let" : "const"} ${hoist.name} = `;
|
|
337
|
+
// Multi-line JSX is parenthesized, as Prettier does, which breaks JSX that does not fit on its line
|
|
338
|
+
const element = (await TreePrinters.printer(JS.Kind.CompilationUnit).print(hoist.element)).trim();
|
|
339
|
+
const parenthesized = hoist.element.kind === JS.Kind.JsxTag && (element.includes("\n") ||
|
|
340
|
+
this.prettier && indent.length - indent.lastIndexOf("\n") - 1 + declarator.length + element.length + 1 > this.printWidth);
|
|
341
|
+
const elementDeclaration = Template.builder().code(declarator + (parenthesized ? "(" : "")).param(hoist.element)
|
|
342
|
+
.code((parenthesized ? ")" : "") + ";").build();
|
|
343
|
+
const hoisted = await elementDeclaration.apply(declaration, new Cursor(declaration, new Cursor(statement, new Cursor(block, this.cursor.parent))));
|
|
344
|
+
if (!hoisted) throw new Error(`Cannot declare ${hoist.name}`);
|
|
345
|
+
return [
|
|
346
|
+
{...statement, element: {...hoisted, prefix} as typeof declaration},
|
|
347
|
+
{...statement, element: {...declaration, prefix: {...prefix, whitespace: indent, comments: []}}}
|
|
348
|
+
];
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// Prettier lays out only the replaced expression, while its line breaks often belong to the
|
|
352
|
+
// enclosing call, as in `expect(\n converted\n).toBe(0)`; lay out the whole statement instead.
|
|
353
|
+
private async withPrettierLayout(block: J.Block, ctx: ExecutionContext): Promise<J.Block> {
|
|
354
|
+
if (this.reformat.size === 0) return block;
|
|
355
|
+
const parent = new Cursor(block, this.cursor.parent);
|
|
356
|
+
const statements: J.Block["statements"][number][] = [];
|
|
357
|
+
let formatted = false;
|
|
358
|
+
for (const statement of block.statements) {
|
|
359
|
+
const ids = await idsWithin(statement.element, this.reformat, ctx);
|
|
360
|
+
if (ids.length === 0) {
|
|
361
|
+
statements.push(statement);
|
|
362
|
+
continue;
|
|
363
|
+
}
|
|
364
|
+
ids.forEach(id => this.reformat.delete(id));
|
|
365
|
+
statements.push({...statement, element: await autoFormat(statement.element, ctx, undefined, new Cursor(statement, parent))});
|
|
366
|
+
formatted = true;
|
|
367
|
+
}
|
|
368
|
+
return formatted ? create(block, draft => {
|
|
369
|
+
draft.statements = statements as any;
|
|
370
|
+
}) : block;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
override async visitVariableDeclarations(declarations: J.VariableDeclarations, ctx: ExecutionContext): Promise<J | undefined> {
|
|
374
|
+
const visited = await super.visitVariableDeclarations(declarations, ctx) as J.VariableDeclarations;
|
|
375
|
+
return this.declarations.has(declarations.id) ? withoutEnzymeTypes(visited, ctx) : visited;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
override async visitFieldAccess(field: J.FieldAccess, ctx: ExecutionContext): Promise<J | undefined> {
|
|
379
|
+
const use = this.uses.get(field.id);
|
|
380
|
+
if (use) return await this.apply(use, field, ctx) ?? field;
|
|
381
|
+
const visited = await super.visitFieldAccess(field, ctx) as J.FieldAccess;
|
|
382
|
+
if (visited.name.element.simpleName === "length" && simpleChain(visited)) {
|
|
383
|
+
const result = await lengthRule.tryOn(this.cursor, visited, {visitor: this});
|
|
384
|
+
if (result) {
|
|
385
|
+
this.converted("mount.find.length", "<inline expression>", "INLINE_DOM_QUERY");
|
|
386
|
+
this.laidOutByPrettier(result);
|
|
387
|
+
return withRenderOptionsOnElementLine(result, ctx);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
return visited;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
|
|
394
|
+
const use = this.uses.get(method.id);
|
|
395
|
+
if (use) return await this.apply(use, method, ctx) ?? method;
|
|
396
|
+
if (this.unmounts.has(method.id)) return withoutEnzymeTypes(method, ctx);
|
|
397
|
+
const visited = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
|
|
398
|
+
if (this.mounts.has(method.id)) {
|
|
399
|
+
const hoisted = this.hoistedMounts.get(method.id);
|
|
400
|
+
const result = hoisted ?
|
|
401
|
+
await this.applyTemplate(Template.builder().code(`render(${hoisted}, {container: globalThis.document.createElement('div')})`).build().configure(after), visited) :
|
|
402
|
+
await mountRule.tryOn(this.cursor, visited, {visitor: this});
|
|
403
|
+
if (!result) return visited;
|
|
404
|
+
this.pending.delete(method.id);
|
|
405
|
+
return withRenderOptionsOnElementLine(result, ctx);
|
|
406
|
+
}
|
|
407
|
+
if (visited.name.simpleName === "mount" && mountedElement(visited) && statementPosition(this.cursor)) {
|
|
408
|
+
const result = await mountRule.tryOn(this.cursor, visited, {visitor: this});
|
|
409
|
+
if (result) {
|
|
410
|
+
this.converted("mount", enclosingScope(this.cursor), "MOUNT_STATEMENT");
|
|
411
|
+
this.laidOutByPrettier(result);
|
|
412
|
+
return withRenderOptionsOnElementLine(result, ctx);
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
if (visited.name.simpleName === "exists" && simpleChain(visited)) {
|
|
416
|
+
const result = await (this.callArgument(visited) ? existsArgumentRule : existsRule).tryOn(this.cursor, visited, {visitor: this});
|
|
417
|
+
if (result) {
|
|
418
|
+
this.converted("mount.find.exists", "<inline expression>", "INLINE_DOM_QUERY");
|
|
419
|
+
this.laidOutByPrettier(result);
|
|
420
|
+
return withRenderOptionsOnElementLine(result, ctx);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
return visited;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
private async mountMatches(mount: string, block: J.Block, ctx: ExecutionContext): Promise<boolean> {
|
|
427
|
+
let mounted = false;
|
|
428
|
+
await new class extends JavaScriptVisitor<ExecutionContext> {
|
|
429
|
+
override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
|
|
430
|
+
if (method.id === mount && await mountPattern.match(method, this.cursor)) mounted = true;
|
|
431
|
+
return super.visitMethodInvocation(method, ctx);
|
|
432
|
+
}
|
|
433
|
+
}().visit(block, ctx, this.cursor.parent);
|
|
434
|
+
return mounted;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
private async apply(read: WrapperRead, node: J, ctx: ExecutionContext): Promise<J | undefined> {
|
|
438
|
+
const result = await this.applyTemplate(this.readTemplate(read, node), node);
|
|
439
|
+
if (!result) return undefined;
|
|
440
|
+
this.pending.delete(node.id);
|
|
441
|
+
this.laidOutByPrettier(result);
|
|
442
|
+
if (read.vacuous) {
|
|
443
|
+
this.rows.push({sourcePath: this.sourcePath, scope: enclosingScope(this.cursor), api: "find", status: "REVIEW", reason: "VACUOUS_ASSERTION",
|
|
444
|
+
suggestedAction: "The assertion holds for any Enzyme wrapper and any node list; assert the expected number of elements instead."});
|
|
445
|
+
}
|
|
446
|
+
return withoutEnzymeTypes(result, ctx);
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
private async applyTemplate(replacement: Template, node: J): Promise<J | undefined> {
|
|
450
|
+
return replacement.apply(node, this.cursor, {bindings: await replacement.resolveBindings(this)});
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
private readTemplate(read: WrapperRead, node: J): Template {
|
|
454
|
+
const code = Template.builder();
|
|
455
|
+
const nodes = () => code.param(read.wrapper).code(".container.querySelectorAll(").param(read.selector!).code(")");
|
|
456
|
+
// Enzyme throws where a single-node method finds no node; so does a non-null element here
|
|
457
|
+
const element = (nonNull: boolean) => {
|
|
458
|
+
const assertion = nonNull && this.typescript ? "!" : "";
|
|
459
|
+
if (read.index === "last") {
|
|
460
|
+
code.code("Array.from(");
|
|
461
|
+
return nodes().code(").pop()" + assertion);
|
|
462
|
+
}
|
|
463
|
+
if (read.index !== undefined && read.index !== "first") return nodes().code("[").param(read.index).code("]");
|
|
464
|
+
return code.param(read.wrapper).code(".container.querySelector(").param(read.selector!).code(")" + assertion);
|
|
465
|
+
};
|
|
466
|
+
const parenthesized = (build: () => void) => {
|
|
467
|
+
const bare = this.callArgument(node);
|
|
468
|
+
if (!bare) code.code("(");
|
|
469
|
+
build();
|
|
470
|
+
return code.code(bare ? "" : ")").build();
|
|
471
|
+
};
|
|
472
|
+
// Enzyme finds nothing within a position it has no element at
|
|
473
|
+
const within = () => element(false).code("?.querySelectorAll(").param(read.within!).code(").length ?? 0");
|
|
474
|
+
switch (read.use) {
|
|
475
|
+
case "length":
|
|
476
|
+
if (read.within) return parenthesized(within);
|
|
477
|
+
return nodes().code(".length").build();
|
|
478
|
+
case "exists":
|
|
479
|
+
if (read.within) return parenthesized(() => {
|
|
480
|
+
code.code("(");
|
|
481
|
+
within().code(") > 0");
|
|
482
|
+
});
|
|
483
|
+
return parenthesized(() => nodes().code(".length > 0"));
|
|
484
|
+
case "positionExists":
|
|
485
|
+
return parenthesized(() => {
|
|
486
|
+
if (read.index === "first") code.param(read.wrapper).code(".container.querySelector(").param(read.selector!).code(") !== null");
|
|
487
|
+
else if (read.index === "last") nodes().code(".length > 0");
|
|
488
|
+
else nodes().code("[").param(read.index!).code("] !== undefined");
|
|
489
|
+
});
|
|
490
|
+
case "nodes":
|
|
491
|
+
return nodes().build();
|
|
492
|
+
// An element's text content is never null, though its type allows it
|
|
493
|
+
case "text":
|
|
494
|
+
return code.param(read.wrapper).code(".container.textContent" + (read.unasserted && this.typescript ? "!" : "")).build();
|
|
495
|
+
case "selectorText":
|
|
496
|
+
if (read.unasserted) return element(true).code(".textContent" + (this.typescript ? "!" : "")).build();
|
|
497
|
+
return element(false).code("?.textContent").build();
|
|
498
|
+
case "html":
|
|
499
|
+
return element(!!read.unasserted).code(read.unasserted ? ".outerHTML" : "?.outerHTML").build();
|
|
500
|
+
case "hasClass":
|
|
501
|
+
return element(true).code(".classList.contains(").param(read.className!).code(")").build();
|
|
502
|
+
case "setProps":
|
|
503
|
+
code.param(read.wrapper).code(`.rerender(${read.reassigned ? `(${read.element} = ` : ""}cloneElement(${read.element}, `);
|
|
504
|
+
return code.param(read.props!).code(read.reassigned ? ")))" : "))").build().configure({
|
|
505
|
+
context: ['import {cloneElement} from "react";'],
|
|
506
|
+
dependencies: {"@types/react": "16.14.62"}
|
|
507
|
+
});
|
|
508
|
+
case "simulate":
|
|
509
|
+
if (read.nativeEvent) {
|
|
510
|
+
code.code("fireEvent(");
|
|
511
|
+
element(true);
|
|
512
|
+
code.code(`, Object.defineProperties(createEvent.${read.event}(`);
|
|
513
|
+
element(true);
|
|
514
|
+
code.code("), {");
|
|
515
|
+
read.nativeEvent.forEach(([name, value], i) => code.code(`${i ? ", " : ""}${name}: {value: `).param(value).code("}"));
|
|
516
|
+
return code.code("}))").build().configure({
|
|
517
|
+
context: [`import {createEvent, fireEvent} from "${RTL}";`],
|
|
518
|
+
dependencies: {[RTL]: "12.1.5", "@types/react": "16.14.62"}
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
code.code(`fireEvent.${read.event}(`);
|
|
522
|
+
element(true);
|
|
523
|
+
if (read.eventInit) code.code(", ").param(read.eventInit);
|
|
524
|
+
return code.code(")").build().configure({
|
|
525
|
+
context: [`import {fireEvent} from "${RTL}";`],
|
|
526
|
+
dependencies: {[RTL]: "12.1.5", "@types/react": "16.14.62"}
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// A comparison needs no parentheses of its own as a call argument, and Prettier removes them there
|
|
532
|
+
private callArgument(node: J): boolean {
|
|
533
|
+
const parent = this.cursor.parentTree()?.value as J | undefined;
|
|
534
|
+
return parent?.kind === J.Kind.MethodInvocation &&
|
|
535
|
+
(parent as J.MethodInvocation).arguments.elements.some(argument => argument.element.id === node.id);
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
private laidOutByPrettier(node: J): void {
|
|
539
|
+
if (this.prettier) this.reformat.add(node.id);
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
private converted(api: string, scope: string, reason: string): void {
|
|
543
|
+
maybeRemoveImport(this, ENZYME);
|
|
544
|
+
this.rows.push({sourcePath: this.sourcePath, scope, api, status: "CONVERTED", reason,
|
|
545
|
+
suggestedAction: "Run the migrated test and review whether an accessible RTL query would better express its intent."});
|
|
546
|
+
}
|
|
547
|
+
}());
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
async recipeList() {
|
|
551
|
+
return [...ADDS_RTL ? [await addDependency(RTL_ADDITION)] : [], new FindEnzymeUsage()];
|
|
552
|
+
}
|
|
553
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import {Column, Cursor} from "@openrewrite/rewrite";
|
|
2
|
+
import {JS} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {isIdentifier, J, Type} from "@openrewrite/rewrite/java";
|
|
4
|
+
|
|
5
|
+
export const ENZYME = "enzyme";
|
|
6
|
+
export const ENZYME_GUIDE = "https://testing-library.com/docs/react-testing-library/migrate-from-enzyme/";
|
|
7
|
+
export const ENZYME_USAGE_TABLE = "org.openrewrite.react.table.EnzymeUsages";
|
|
8
|
+
|
|
9
|
+
export class EnzymeUsageRow {
|
|
10
|
+
@Column({displayName: "Source path", description: "The file containing the Enzyme usage."})
|
|
11
|
+
sourcePath!: string;
|
|
12
|
+
|
|
13
|
+
@Column({displayName: "Scope", description: "The enclosing test or function, or <module> when no name is available."})
|
|
14
|
+
scope!: string;
|
|
15
|
+
|
|
16
|
+
@Column({displayName: "API", description: "The Enzyme API or module reference found."})
|
|
17
|
+
api!: string;
|
|
18
|
+
|
|
19
|
+
@Column({displayName: "Status", description: "REVIEW for remaining usage, or CONVERTED for a migrated expression."})
|
|
20
|
+
status!: string;
|
|
21
|
+
|
|
22
|
+
@Column({displayName: "Reason", description: "A stable reason code explaining the migration action or blocker."})
|
|
23
|
+
reason!: string;
|
|
24
|
+
|
|
25
|
+
@Column({displayName: "Suggested action", description: "The next step for migrating or reviewing this usage."})
|
|
26
|
+
suggestedAction!: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function enzymeModule(value: unknown): value is string {
|
|
30
|
+
return typeof value === "string" && (value === ENZYME || value.startsWith("enzyme/") ||
|
|
31
|
+
(value === "enzyme-to-json" || value.startsWith("enzyme-to-json/")) || /^(?:@[^/]+\/)?enzyme-adapter-/.test(value));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function enzymeMethod(method: J.MethodInvocation): string | undefined {
|
|
35
|
+
const type = method.methodType;
|
|
36
|
+
if (!type) return undefined;
|
|
37
|
+
const owner = Type.FullyQualified.getFullyQualifiedName(type.declaringType);
|
|
38
|
+
return owner === ENZYME || owner.startsWith(`${ENZYME}.`) ? type.name : undefined;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function enzymeWrapper(type: Type | undefined): boolean {
|
|
42
|
+
return !!type && Type.isOfTypeWithName(type, true,
|
|
43
|
+
name => /^enzyme\.(?:ReactWrapper|ShallowWrapper|CommonWrapper)$/.test(name));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function migrationReason(api: string): {reason: string, suggestedAction: string} {
|
|
47
|
+
if (api === "shallow" || api === "dive") {
|
|
48
|
+
return {reason: "SHALLOW_RENDERING", suggestedAction: "Review child rendering and effects before replacing shallow rendering with RTL render."};
|
|
49
|
+
}
|
|
50
|
+
if (["state", "setState", "instance", "invoke"].includes(api)) {
|
|
51
|
+
return {reason: "INTERNAL_STATE", suggestedAction: "Replace implementation-detail access with user interactions and observable DOM assertions."};
|
|
52
|
+
}
|
|
53
|
+
if (api === "simulate") {
|
|
54
|
+
return {reason: "UNSUPPORTED_EVENT", suggestedAction: "Review event payloads and async control flow before selecting user-event or fireEvent."};
|
|
55
|
+
}
|
|
56
|
+
if (api === "find" || api === "findWhere" || api === "filterWhere") {
|
|
57
|
+
return {reason: "SELECTOR_REVIEW", suggestedAction: "Review selector scope, component versus DOM matching, and zero/one/multiple-match behavior."};
|
|
58
|
+
}
|
|
59
|
+
if (api === "mount") {
|
|
60
|
+
return {reason: "RENDER_REVIEW", suggestedAction: "Review every use of the wrapper and its shared setup before replacing mount with RTL render."};
|
|
61
|
+
}
|
|
62
|
+
if (api === "render") {
|
|
63
|
+
return {reason: "STATIC_RENDERING", suggestedAction: "Review static HTML and Cheerio assertions before migrating to RTL DOM rendering."};
|
|
64
|
+
}
|
|
65
|
+
if (api === "configure") {
|
|
66
|
+
return {reason: "ENZYME_SETUP", suggestedAction: "Keep Enzyme setup until no tests or helpers in the owning package need it."};
|
|
67
|
+
}
|
|
68
|
+
return {reason: "WRAPPER_API", suggestedAction: "Review this Enzyme wrapper API for an equivalent RTL interaction or DOM assertion."};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function enclosingScope(start: Cursor): string {
|
|
72
|
+
for (let cursor = start.parent; cursor; cursor = cursor.parent) {
|
|
73
|
+
const node = cursor.value as J;
|
|
74
|
+
if (node?.kind === J.Kind.MethodInvocation) {
|
|
75
|
+
const call = node as J.MethodInvocation;
|
|
76
|
+
const receiver = call.select?.element;
|
|
77
|
+
if (["it", "test", "describe"].includes(call.name.simpleName) ||
|
|
78
|
+
(["only", "skip"].includes(call.name.simpleName) && receiver && isIdentifier(receiver) &&
|
|
79
|
+
["it", "test", "describe"].includes(receiver.simpleName))) {
|
|
80
|
+
const first = call.arguments.elements[0]?.element;
|
|
81
|
+
if (first?.kind === J.Kind.Literal && typeof (first as J.Literal).value === "string") {
|
|
82
|
+
return String((first as J.Literal).value);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (node?.kind === J.Kind.NamedVariable) {
|
|
87
|
+
const variable = node as J.VariableDeclarations.NamedVariable;
|
|
88
|
+
if ((variable.initializer?.element.kind === JS.Kind.ArrowFunction || variable.initializer?.element.kind === J.Kind.Lambda) &&
|
|
89
|
+
isIdentifier(variable.name)) return variable.name.simpleName;
|
|
90
|
+
}
|
|
91
|
+
if (node?.kind === J.Kind.MethodDeclaration) return (node as J.MethodDeclaration).name.simpleName;
|
|
92
|
+
}
|
|
93
|
+
return "<module>";
|
|
94
|
+
}
|