@openrewrite/recipes-react 0.15.0 → 0.17.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.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/migration/cra-to-vite/add-vite-config.d.ts +7 -0
- package/dist/migration/cra-to-vite/add-vite-config.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/add-vite-config.js +58 -1
- package/dist/migration/cra-to-vite/add-vite-config.js.map +1 -1
- package/dist/migration/cra-to-vite/cra-file-gate.d.ts +3 -0
- package/dist/migration/cra-to-vite/cra-file-gate.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-file-gate.js +10 -0
- package/dist/migration/cra-to-vite/cra-file-gate.js.map +1 -0
- package/dist/migration/cra-to-vite/cra-runtime.d.ts +2 -0
- package/dist/migration/cra-to-vite/cra-runtime.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-runtime.js +24 -0
- package/dist/migration/cra-to-vite/cra-runtime.js.map +1 -0
- package/dist/migration/cra-to-vite/cra-script.d.ts +8 -0
- package/dist/migration/cra-to-vite/cra-script.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-script.js +82 -0
- package/dist/migration/cra-to-vite/cra-script.js.map +1 -0
- package/dist/migration/cra-to-vite/cra-to-vite.d.ts +2 -1
- package/dist/migration/cra-to-vite/cra-to-vite.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/cra-to-vite.js +23 -16
- package/dist/migration/cra-to-vite/cra-to-vite.js.map +1 -1
- package/dist/migration/cra-to-vite/cra-typecheck.d.ts +4 -0
- package/dist/migration/cra-to-vite/cra-typecheck.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/cra-typecheck.js +35 -0
- package/dist/migration/cra-to-vite/cra-typecheck.js.map +1 -0
- package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js +22 -29
- package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
- package/dist/migration/cra-to-vite/index.d.ts +8 -2
- package/dist/migration/cra-to-vite/index.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/index.js +17 -2
- package/dist/migration/cra-to-vite/index.js.map +1 -1
- package/dist/migration/cra-to-vite/migrate-cra-package.d.ts +17 -0
- package/dist/migration/cra-to-vite/migrate-cra-package.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/migrate-cra-package.js +181 -0
- package/dist/migration/cra-to-vite/migrate-cra-package.js.map +1 -0
- package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts +9 -0
- package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js +66 -0
- package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js.map +1 -0
- package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts +49 -0
- package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js +506 -0
- package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js.map +1 -0
- package/dist/migration/cra-to-vite/move-public-index-html.d.ts +2 -0
- package/dist/migration/cra-to-vite/move-public-index-html.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/move-public-index-html.js +12 -7
- package/dist/migration/cra-to-vite/move-public-index-html.js.map +1 -1
- package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts +30 -0
- package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/plan-cra-to-vite.js +428 -0
- package/dist/migration/cra-to-vite/plan-cra-to-vite.js.map +1 -0
- package/dist/migration/cra-to-vite/prepare-cra-package.d.ts +15 -0
- package/dist/migration/cra-to-vite/prepare-cra-package.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/prepare-cra-package.js +100 -0
- package/dist/migration/cra-to-vite/prepare-cra-package.js.map +1 -0
- package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts +12 -0
- package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/remove-cra-configuration.js +85 -0
- package/dist/migration/cra-to-vite/remove-cra-configuration.js.map +1 -0
- package/dist/migration/cra-to-vite/rename-jsx-files.d.ts +20 -0
- package/dist/migration/cra-to-vite/rename-jsx-files.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/rename-jsx-files.js +220 -0
- package/dist/migration/cra-to-vite/rename-jsx-files.js.map +1 -0
- package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/rename-process-env-react-app.js +6 -3
- package/dist/migration/cra-to-vite/rename-process-env-react-app.js.map +1 -1
- package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js +1 -1
- package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js.map +1 -1
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts +11 -4
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js +47 -50
- package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js.map +1 -1
- package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts +3 -0
- package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/resolved-cra-dependency.js +42 -0
- package/dist/migration/cra-to-vite/resolved-cra-dependency.js.map +1 -0
- package/dist/migration/cra-to-vite/scan-cra-projects.d.ts +13 -0
- package/dist/migration/cra-to-vite/scan-cra-projects.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/scan-cra-projects.js +52 -4
- package/dist/migration/cra-to-vite/scan-cra-projects.js.map +1 -1
- package/dist/migration/cra-to-vite/shared.d.ts +2 -15
- package/dist/migration/cra-to-vite/shared.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/shared.js +32 -130
- package/dist/migration/cra-to-vite/shared.js.map +1 -1
- package/dist/migration/cra-to-vite/svg-component.d.ts +5 -0
- package/dist/migration/cra-to-vite/svg-component.d.ts.map +1 -0
- package/dist/migration/cra-to-vite/svg-component.js +60 -0
- package/dist/migration/cra-to-vite/svg-component.js.map +1 -0
- package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/update-react-app-env-types.js +8 -2
- package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -1
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts +3 -2
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.js +28 -29
- package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -1
- package/dist/migration/cra-to-vite/update-tsconfig-for-vite.d.ts.map +1 -1
- package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js +4 -13
- package/dist/migration/cra-to-vite/update-tsconfig-for-vite.js.map +1 -1
- package/dist/react17/migrate-deprecated-lifecycles.js +1 -1
- package/dist/react17/migrate-deprecated-lifecycles.js.map +1 -1
- package/dist/react17/use-new-jsx-transform.d.ts.map +1 -1
- package/dist/react17/use-new-jsx-transform.js +30 -78
- package/dist/react17/use-new-jsx-transform.js.map +1 -1
- package/dist/react18/replace-reactdom-render.d.ts.map +1 -1
- package/dist/react18/replace-reactdom-render.js +16 -8
- package/dist/react18/replace-reactdom-render.js.map +1 -1
- package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
- package/dist/react18/replace-unmount-component-at-node.js +62 -20
- package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
- package/dist/react19/replace-default-props.d.ts.map +1 -1
- package/dist/react19/replace-default-props.js +10 -13
- package/dist/react19/replace-default-props.js.map +1 -1
- package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
- package/dist/react19/replace-react-shallow-renderer.js +1 -6
- package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
- package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
- package/dist/refactoring/create-class-to-es6.js +4 -7
- package/dist/refactoring/create-class-to-es6.js.map +1 -1
- package/dist/refactoring/create-element-to-jsx.d.ts.map +1 -1
- package/dist/refactoring/create-element-to-jsx.js +3 -4
- package/dist/refactoring/create-element-to-jsx.js.map +1 -1
- package/dist/refactoring/prop-types-to-typescript.js +2 -3
- package/dist/refactoring/prop-types-to-typescript.js.map +1 -1
- package/dist/refactoring/pure-render-mixin.d.ts.map +1 -1
- package/dist/refactoring/pure-render-mixin.js +3 -6
- package/dist/refactoring/pure-render-mixin.js.map +1 -1
- package/dist/testing/enzyme-constant-strings.d.ts +12 -0
- package/dist/testing/enzyme-constant-strings.d.ts.map +1 -0
- package/dist/testing/enzyme-constant-strings.js +101 -0
- package/dist/testing/enzyme-constant-strings.js.map +1 -0
- package/dist/testing/enzyme-host-components.d.ts +14 -0
- package/dist/testing/enzyme-host-components.d.ts.map +1 -0
- package/dist/testing/enzyme-host-components.js +248 -0
- package/dist/testing/enzyme-host-components.js.map +1 -0
- package/dist/testing/enzyme-portals.d.ts +38 -0
- package/dist/testing/enzyme-portals.d.ts.map +1 -0
- package/dist/testing/enzyme-portals.js +226 -0
- package/dist/testing/enzyme-portals.js.map +1 -0
- package/dist/testing/enzyme-selector-names.d.ts +9 -0
- package/dist/testing/enzyme-selector-names.d.ts.map +1 -0
- package/dist/testing/enzyme-selector-names.js +50 -0
- package/dist/testing/enzyme-selector-names.js.map +1 -0
- package/dist/testing/enzyme-to-react-testing-library.d.ts +80 -12
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +447 -135
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-usage.d.ts.map +1 -1
- package/dist/testing/enzyme-usage.js +27 -4
- package/dist/testing/enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +23 -8
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +291 -169
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
- package/dist/util/java-recipe-proxy.d.ts +16 -0
- package/dist/util/java-recipe-proxy.d.ts.map +1 -0
- package/dist/util/java-recipe-proxy.js +85 -0
- package/dist/util/java-recipe-proxy.js.map +1 -0
- package/dist/util/module-imports.d.ts +13 -0
- package/dist/util/module-imports.d.ts.map +1 -0
- package/dist/util/module-imports.js +60 -0
- package/dist/util/module-imports.js.map +1 -0
- package/dist/util/react-class.d.ts +1 -0
- package/dist/util/react-class.d.ts.map +1 -1
- package/dist/util/react-class.js +3 -2
- package/dist/util/react-class.js.map +1 -1
- package/package.json +4 -4
- package/src/index.ts +2 -1
- package/src/migration/cra-to-vite/add-vite-config.ts +53 -1
- package/src/migration/cra-to-vite/cra-file-gate.ts +8 -0
- package/src/migration/cra-to-vite/cra-runtime.ts +16 -0
- package/src/migration/cra-to-vite/cra-script.ts +61 -0
- package/src/migration/cra-to-vite/cra-to-vite.ts +25 -36
- package/src/migration/cra-to-vite/cra-typecheck.ts +33 -0
- package/src/migration/cra-to-vite/find-cra-config-blockers.ts +23 -28
- package/src/migration/cra-to-vite/index.ts +10 -2
- package/src/migration/cra-to-vite/migrate-cra-package.ts +127 -0
- package/src/migration/cra-to-vite/migrate-cra-svg-imports.ts +41 -0
- package/src/migration/cra-to-vite/migrate-cra-tests-to-vitest.ts +376 -0
- package/src/migration/cra-to-vite/move-public-index-html.ts +12 -7
- package/src/migration/cra-to-vite/plan-cra-to-vite.ts +283 -0
- package/src/migration/cra-to-vite/prepare-cra-package.ts +86 -0
- package/src/migration/cra-to-vite/remove-cra-configuration.ts +64 -0
- package/src/migration/cra-to-vite/rename-jsx-files.ts +155 -0
- package/src/migration/cra-to-vite/rename-process-env-react-app.ts +6 -3
- package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +1 -1
- package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +48 -54
- package/src/migration/cra-to-vite/resolved-cra-dependency.ts +41 -0
- package/src/migration/cra-to-vite/scan-cra-projects.ts +57 -6
- package/src/migration/cra-to-vite/shared.ts +35 -146
- package/src/migration/cra-to-vite/svg-component.ts +39 -0
- package/src/migration/cra-to-vite/update-react-app-env-types.ts +11 -4
- package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +30 -41
- package/src/migration/cra-to-vite/update-tsconfig-for-vite.ts +6 -13
- package/src/react17/migrate-deprecated-lifecycles.ts +2 -2
- package/src/react17/use-new-jsx-transform.ts +30 -72
- package/src/react18/replace-reactdom-render.ts +17 -8
- package/src/react18/replace-unmount-component-at-node.ts +78 -32
- package/src/react19/replace-default-props.ts +11 -15
- package/src/react19/replace-react-shallow-renderer.ts +2 -7
- package/src/refactoring/create-class-to-es6.ts +6 -9
- package/src/refactoring/create-element-to-jsx.ts +4 -6
- package/src/refactoring/prop-types-to-typescript.ts +4 -4
- package/src/refactoring/pure-render-mixin.ts +4 -7
- package/src/testing/enzyme-constant-strings.ts +95 -0
- package/src/testing/enzyme-host-components.ts +287 -0
- package/src/testing/enzyme-portals.ts +279 -0
- package/src/testing/enzyme-selector-names.ts +59 -0
- package/src/testing/enzyme-to-react-testing-library.ts +584 -140
- package/src/testing/enzyme-usage.ts +29 -4
- package/src/testing/enzyme-wrapper-scope.ts +309 -151
- package/src/util/java-recipe-proxy.ts +81 -0
- package/src/util/module-imports.ts +60 -0
- package/src/util/react-class.ts +2 -1
|
@@ -1,25 +1,203 @@
|
|
|
1
|
-
import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, ScanningRecipe, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
-
import {
|
|
1
|
+
import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, or, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
|
+
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
3
|
import {Expression, J} from "@openrewrite/rewrite/java";
|
|
4
4
|
import {create} from "mutative";
|
|
5
5
|
import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
|
|
6
6
|
import {readFileSync} from "fs";
|
|
7
7
|
import {dirname, join} from "path";
|
|
8
|
-
import {satisfies, validRange} from "semver";
|
|
8
|
+
import {satisfies, valid, validRange} from "semver";
|
|
9
9
|
import {FindEnzymeUsage} from "../search/find-enzyme-usage";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
10
|
+
import {JavaDependencyRecipe, treesOfType} from "../util/java-recipe-proxy";
|
|
11
|
+
import {importBindings} from "../util/module-imports";
|
|
12
|
+
import {ENZYME, ENZYME_USAGE_TABLE, enclosingScope, enzymeMethod, EnzymeUsageRow} from "./enzyme-usage";
|
|
13
|
+
import {HostComponents, hostComponentExports, ImportedExport, importedNames, propsRenderHostElements, relativeImports, rendersHostElements} from "./enzyme-host-components";
|
|
14
|
+
import {moduleFacts, Modules, rendersPortal, resolver} from "./enzyme-portals";
|
|
15
|
+
import {evaluate, stringParts} from "./enzyme-constant-strings";
|
|
16
|
+
import {hostOnlyNames, selectorNames, SelectorNames} from "./enzyme-selector-names";
|
|
17
|
+
import {analyzeWrapperScope, SIMULATED_EVENTS, idsWithin, innermostCall, mountedElement, passesRef, selectorLiteral, simpleChain, statementPosition, variableCursor, withoutEnzymeTypes, withRenderOptionsOnElementLine, wrapperDeclaration, WrapperRead, WrapperUse} from "./enzyme-wrapper-scope";
|
|
12
18
|
|
|
13
19
|
const RTL = "@testing-library/react";
|
|
14
20
|
|
|
15
21
|
const REACT_RANGE = ">=16.9.0 <18";
|
|
16
22
|
|
|
23
|
+
const REACT_18_RANGE = ">=18.0.0 <19";
|
|
24
|
+
|
|
25
|
+
const resolvingReact = (range: string) => [`react@${range}`, `react-dom@${range}`];
|
|
26
|
+
|
|
17
27
|
/** RTL 12 supports React 16.9 to 17, so it goes where Enzyme is used with those. */
|
|
18
28
|
const RTL_ADDITION: AddDependencyOptions = {
|
|
19
29
|
packageName: RTL, version: "^12.1.5", scope: "devDependencies",
|
|
20
|
-
onlyIfDeclaring: ["enzyme"], onlyIfResolving:
|
|
30
|
+
onlyIfDeclaring: ["enzyme"], onlyIfResolving: resolvingReact(REACT_RANGE)
|
|
21
31
|
};
|
|
22
32
|
|
|
33
|
+
/** RTL 16 supports React 18 with `@testing-library/dom` 10 as a peer, which a package must declare itself. */
|
|
34
|
+
const RTL_18_ADDITION: AddDependencyOptions = {...RTL_ADDITION, version: "^16.3.0", onlyIfResolving: resolvingReact(REACT_18_RANGE)};
|
|
35
|
+
|
|
36
|
+
const DOM = "@testing-library/dom";
|
|
37
|
+
const DOM_18_ADDITION: AddDependencyOptions = {...RTL_18_ADDITION, packageName: DOM, version: "^10.4.0"};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The test sources the converter would convert were RTL added to every package that may take it, which the
|
|
41
|
+
* dependency steps read so that they add RTL only where a source converts. The converter sets it while it
|
|
42
|
+
* scans. Mutated in place, as copies of a prepared recipe share it.
|
|
43
|
+
*/
|
|
44
|
+
export interface ConversionForecast {
|
|
45
|
+
converting?: () => Promise<ReadonlySet<string>>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The directory of a `package.json`, such as `packages/ui/`, or `""` at the repository's root. */
|
|
49
|
+
function packageRoot(manifestPath: string): string {
|
|
50
|
+
return manifestPath.slice(0, -"package.json".length);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Each manifest's lockfile scope: the root of the workspace it is a member of, or its own root. A package manager
|
|
55
|
+
* installs a workspace's members together, and `AddDependency` declines the edit for every member when one is
|
|
56
|
+
* kept from it, so a workspace takes RTL as a whole or not at all.
|
|
57
|
+
*/
|
|
58
|
+
export function lockfileScopes(manifests: readonly Json.Document[]): Map<string, string> {
|
|
59
|
+
const scopes = new Map<string, string>();
|
|
60
|
+
for (const manifest of manifests) {
|
|
61
|
+
const root = packageRoot(manifest.sourcePath);
|
|
62
|
+
if (!scopes.has(manifest.sourcePath)) scopes.set(manifest.sourcePath, root);
|
|
63
|
+
// NOTE: the parser lists members from the same base as `sourcePath`, the repository's root, not the workspace's
|
|
64
|
+
for (const member of findNodeResolutionResult(manifest)?.workspacePackagePaths ?? []) {
|
|
65
|
+
scopes.set(member.replace(/^\.\//, ""), root);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return scopes;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Adds a test dependency where Enzyme tests are migrated, with its gates, as Java's `AddDependency` does. */
|
|
72
|
+
abstract class EnzymeTestDependency extends JavaDependencyRecipe {
|
|
73
|
+
/**
|
|
74
|
+
* The package roots, such as `packages/ui/`, whose `package.json` declares the dependency once this run's
|
|
75
|
+
* edit lands, known from the end of `generate` on. Mutated in place, as copies of a prepared recipe share it.
|
|
76
|
+
*/
|
|
77
|
+
readonly landed = new Set<string>();
|
|
78
|
+
|
|
79
|
+
private readonly manifests: Json.Document[] = [];
|
|
80
|
+
|
|
81
|
+
/** The manifests the step admits, which reach the Java recipe only in `generate`, once the forecast is known. */
|
|
82
|
+
private readonly held: Json.Document[] = [];
|
|
83
|
+
|
|
84
|
+
protected constructor(private readonly addition: AddDependencyOptions, private readonly forecast: ConversionForecast) {
|
|
85
|
+
super("org.openrewrite.javascript.AddDependency", addition);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
override initialValue(): number {
|
|
89
|
+
this.landed.clear();
|
|
90
|
+
this.manifests.length = 0;
|
|
91
|
+
this.held.length = 0;
|
|
92
|
+
return super.initialValue();
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The package roots that would take the dependency, such as `packages/ui/`, known once the scan is done. */
|
|
96
|
+
candidates(): Set<string> {
|
|
97
|
+
return new Set(this.manifests.map(manifest => packageRoot(manifest.sourcePath)));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// PERF: only manifests the edit's gate admits are visited again, one RPC round trip each; a monorepo
|
|
101
|
+
// such as next.js holds thousands of fixture manifests
|
|
102
|
+
protected override scanned(manifest: SourceFile): boolean {
|
|
103
|
+
if (manifest.kind !== Json.Kind.Document || !/(^|\/)package\.json$/.test(manifest.sourcePath)) return true;
|
|
104
|
+
if (!this.admits(manifest as Json.Document)) return false;
|
|
105
|
+
if (this.addition.onlyIfDeclaring!.some(name => declares(manifest as Json.Document, name))) this.manifests.push(manifest as Json.Document);
|
|
106
|
+
this.held.push(manifest as Json.Document);
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Whether the dependency may go into this `package.json`, beyond the gates `AddDependency` applies itself. */
|
|
111
|
+
protected admits(_manifest: Json.Document): boolean {
|
|
112
|
+
return true;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// NOTE: `AddDependency` decides each edit and regenerates the lockfile while it generates, declining a
|
|
116
|
+
// package whose package manager rejects the edit, such as an npm peer conflict. Its editor then returns
|
|
117
|
+
// that decision for a manifest, and the same one again when the run visits it.
|
|
118
|
+
override async generate(acc: number, ctx: ExecutionContext): Promise<SourceFile[]> {
|
|
119
|
+
// Without a forecast, as when the step runs alone, every admitted manifest goes on as before
|
|
120
|
+
const converting = await this.forecast.converting?.();
|
|
121
|
+
const scopes = lockfileScopes(this.held);
|
|
122
|
+
const forwarded = new Set(this.held.filter(manifest => {
|
|
123
|
+
const scope = scopes.get(manifest.sourcePath) ?? packageRoot(manifest.sourcePath);
|
|
124
|
+
return !converting || [...converting].some(source => source.startsWith(scope));
|
|
125
|
+
}));
|
|
126
|
+
const scanner = await this.java.scanner(acc);
|
|
127
|
+
for (const manifest of forwarded) await scanner.visit(manifest, ctx);
|
|
128
|
+
const kept = this.manifests.filter(manifest => forwarded.has(manifest));
|
|
129
|
+
this.manifests.length = 0;
|
|
130
|
+
this.manifests.push(...kept);
|
|
131
|
+
const generated = await super.generate(acc, ctx);
|
|
132
|
+
const editor = await this.java.editorWithData(acc);
|
|
133
|
+
for (const manifest of this.manifests) {
|
|
134
|
+
const edited = await editor.visit<Json.Document>(manifest, ctx);
|
|
135
|
+
if (edited && edited !== manifest && declares(edited, this.addition.packageName)) this.landed.add(manifest.sourcePath.slice(0, -"package.json".length));
|
|
136
|
+
}
|
|
137
|
+
return generated;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Adds {@link RTL_ADDITION}. */
|
|
142
|
+
export class AddTestingLibraryReact extends EnzymeTestDependency {
|
|
143
|
+
readonly name = "org.openrewrite.react.migrate.add-testing-library-react";
|
|
144
|
+
readonly displayName = "Add `@testing-library/react` where Enzyme tests are migrated";
|
|
145
|
+
readonly description = "Adds `@testing-library/react` 12 as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 16.9 to 17.";
|
|
146
|
+
|
|
147
|
+
constructor(forecast: ConversionForecast = {}) {
|
|
148
|
+
super(RTL_ADDITION, forecast);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** Adds {@link RTL_18_ADDITION}. */
|
|
153
|
+
export class AddTestingLibraryReact18 extends EnzymeTestDependency {
|
|
154
|
+
readonly name = "org.openrewrite.react.migrate.add-testing-library-react-18";
|
|
155
|
+
readonly displayName = "Add `@testing-library/react` 16 where Enzyme tests on React 18 are migrated";
|
|
156
|
+
readonly description = "Adds `@testing-library/react` 16 as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 18.";
|
|
157
|
+
|
|
158
|
+
constructor(forecast: ConversionForecast = {}) {
|
|
159
|
+
super(RTL_18_ADDITION, forecast);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Adds {@link DOM_18_ADDITION}, the peer of {@link RTL_18_ADDITION}. */
|
|
164
|
+
export class AddTestingLibraryDom18 extends EnzymeTestDependency {
|
|
165
|
+
readonly name = "org.openrewrite.react.migrate.add-testing-library-dom-18";
|
|
166
|
+
readonly displayName = "Add `@testing-library/dom` where Enzyme tests on React 18 are migrated";
|
|
167
|
+
readonly description = "Adds `@testing-library/dom` 10, the peer of `@testing-library/react` 16, as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 18.";
|
|
168
|
+
|
|
169
|
+
constructor(forecast: ConversionForecast = {}) {
|
|
170
|
+
super(DOM_18_ADDITION, forecast);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// NOTE: an RTL other than 16 depends on its own `@testing-library/dom`, and the converter leaves its package alone.
|
|
174
|
+
// Only a manifest the step would edit is kept from the Java recipe, which regenerates a workspace's lockfile from
|
|
175
|
+
// every member it scanned: one keeping a member back declines the edit for its siblings too.
|
|
176
|
+
protected override admits(manifest: Json.Document): boolean {
|
|
177
|
+
const rtl = declaration(manifest, RTL);
|
|
178
|
+
if (rtl === undefined || !declares(manifest, ENZYME) || declares(manifest, DOM)) return true;
|
|
179
|
+
const resolved = rtl.resolved?.version.match(/^(\d+)\./)?.[1];
|
|
180
|
+
if (resolved !== undefined) return Number(resolved) === 16;
|
|
181
|
+
const version = declaredVersion(rtl.versionConstraint);
|
|
182
|
+
return version !== undefined && version !== "unsupported" && version.major === 16;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** The package roots where the run added an RTL: RTL 12, or RTL 16 where its peer `@testing-library/dom` landed too. */
|
|
187
|
+
export function rtlLanded(rtl: ReadonlySet<string>, rtl18: ReadonlySet<string>, dom18: ReadonlySet<string>): ReadonlySet<string> {
|
|
188
|
+
return new Set([...rtl, ...[...rtl18].filter(root => dom18.has(root))]);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function declaration(manifest: Json.Document, name: string) {
|
|
192
|
+
const resolution = findNodeResolutionResult(manifest);
|
|
193
|
+
return [...resolution?.dependencies ?? [], ...resolution?.devDependencies ?? [],
|
|
194
|
+
...resolution?.optionalDependencies ?? [], ...resolution?.peerDependencies ?? []].find(dep => dep.name === name);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function declares(manifest: Json.Document, name: string): boolean {
|
|
198
|
+
return declaration(manifest, name) !== undefined;
|
|
199
|
+
}
|
|
200
|
+
|
|
23
201
|
/**
|
|
24
202
|
* Older hosts drop the `onlyIfResolving` option they do not know, which would add RTL to every
|
|
25
203
|
* package declaring Enzyme, so RTL is only added where the host has it.
|
|
@@ -57,6 +235,33 @@ export function rewriteVersion(resolved: string, cache: Record<string, {filename
|
|
|
57
235
|
return undefined;
|
|
58
236
|
}
|
|
59
237
|
|
|
238
|
+
type DocumentReference = "document" | "globalThis.document";
|
|
239
|
+
|
|
240
|
+
/** How a render at `cursor` reaches the global `document` without a local binding capturing it. */
|
|
241
|
+
function documentAt(cursor: Cursor): DocumentReference | undefined {
|
|
242
|
+
const scope = scopeOf(cursor);
|
|
243
|
+
if (!scope.declares("document", "value")) return "document";
|
|
244
|
+
return scope.declares("globalThis", "value") ? undefined : "globalThis.document";
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Whether a source is laid out as its Prettier config would lay it out, judged by its indentation. A
|
|
249
|
+
* package can declare a config, such as for its styles, while another formatter, such as ESLint, lays out
|
|
250
|
+
* its tests, and converted statements then keep that layout instead of Prettier's.
|
|
251
|
+
*/
|
|
252
|
+
async function formattedBy(cu: JS.CompilationUnit, style: PrettierStyle): Promise<boolean> {
|
|
253
|
+
const detector = Autodetect.detector();
|
|
254
|
+
await detector.sampleJavaScript(cu);
|
|
255
|
+
const detected = detector.getTabsAndIndentsStyle();
|
|
256
|
+
const useTabs = style.config.useTabs === true;
|
|
257
|
+
const tabWidth = typeof style.config.tabWidth === "number" ? style.config.tabWidth : 2;
|
|
258
|
+
return detected.useTabCharacter === useTabs && (useTabs || detected.indentSize === tabWidth);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function renderOptions(document: DocumentReference): string {
|
|
262
|
+
return `{container: ${document}.createElement('div')}`;
|
|
263
|
+
}
|
|
264
|
+
|
|
60
265
|
/** A wrapper's rendered element, declared ahead of the wrapper for `setProps` to clone. */
|
|
61
266
|
interface HoistedElement {
|
|
62
267
|
name: string;
|
|
@@ -78,57 +283,131 @@ interface PackageDeclarations {
|
|
|
78
283
|
reactDom: Declaration;
|
|
79
284
|
rtl: Declaration;
|
|
80
285
|
enzyme: boolean;
|
|
81
|
-
/**
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
286
|
+
/** The names of every package it depends on, in any dependency section. */
|
|
287
|
+
dependencies: ReadonlySet<string>;
|
|
288
|
+
/** Whether its lockfile resolves a package that puts styles into the root node of a render's container. */
|
|
289
|
+
rootStyles: boolean;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Packages whose components insert a `<style>` into the root node of the element they render, by the versions that
|
|
294
|
+
* do. In a detached container that root is the container itself, so its `textContent` and `innerHTML` show the
|
|
295
|
+
* style, while Enzyme's `text()` and `html()` read only the nodes React rendered. `@ant-design/icons` does from
|
|
296
|
+
* 5.1.1, for shadow DOM support, and antd 5 bundles it.
|
|
297
|
+
*/
|
|
298
|
+
const ROOT_STYLES: ReadonlyMap<string, string> = new Map([["@ant-design/icons", ">=5.1.1"]]);
|
|
299
|
+
|
|
300
|
+
/** Whether the tests of a source file render components that insert styles into a detached container, as {@link ROOT_STYLES} lists. */
|
|
301
|
+
export function injectsRootStyles(packages: Packages, sourcePath: string): boolean {
|
|
302
|
+
return [...packages.entries()].some(([root, declarations]) => sourcePath.startsWith(root) && declarations.rootStyles);
|
|
86
303
|
}
|
|
87
304
|
|
|
305
|
+
/** The reads of a whole container, which see what a component inserts into it besides what React renders. */
|
|
306
|
+
const CONTAINER_READS: ReadonlySet<WrapperUse> = new Set<WrapperUse>(["text", "rootHtml", "snapshot"]);
|
|
307
|
+
|
|
88
308
|
/** Package roots, such as `packages/ui/`, mapped to their declarations. */
|
|
89
309
|
type Packages = Map<string, PackageDeclarations>;
|
|
90
310
|
|
|
311
|
+
interface Scanned {
|
|
312
|
+
packages: Packages;
|
|
313
|
+
components: HostComponents;
|
|
314
|
+
modules: Modules;
|
|
315
|
+
/** The words of each source's strings, for the selectors whose ancestor compounds name no tag. */
|
|
316
|
+
names: Map<string, SelectorNames>;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** A dry run of the editor: the package roots it takes RTL to have, and the sources it converts. */
|
|
320
|
+
interface DryRun {
|
|
321
|
+
landed: ReadonlySet<string>;
|
|
322
|
+
converted: Set<string>;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** The Enzyme render a converted wrapper comes from. */
|
|
326
|
+
type Render = "mount" | "shallow";
|
|
327
|
+
|
|
328
|
+
/** A render that a converted wrapper is created by, and how its container reaches `document`. */
|
|
329
|
+
interface ConvertedRender {
|
|
330
|
+
document: DocumentReference;
|
|
331
|
+
api: Render;
|
|
332
|
+
/** Whether RTL renders into its default container, attached to the document, for React 16 to receive dispatched events. */
|
|
333
|
+
attached: boolean;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* What a converted wrapper of each Enzyme render may do. A shallow render calls a handler without
|
|
338
|
+
* bubbling or a DOM event, prints a found node as static markup, and shows a component element that
|
|
339
|
+
* `setProps` passes as a placeholder, where a full render shows its DOM.
|
|
340
|
+
*/
|
|
341
|
+
const READS: Record<Render, {simulate: boolean, html: boolean, props: (props: Expression, testImports: ReadonlySet<string>) => boolean}> = {
|
|
342
|
+
mount: {simulate: true, html: true, props: () => true},
|
|
343
|
+
shallow: {simulate: false, html: false, props: propsRenderHostElements}
|
|
344
|
+
};
|
|
345
|
+
|
|
91
346
|
/**
|
|
92
347
|
* The React major version the tests of a source file run with, or 0 where they cannot migrate. A
|
|
93
348
|
* dependency the owning package does not declare comes from the nearest enclosing package that
|
|
94
|
-
* does, where Node resolves it from. Where the run
|
|
95
|
-
*
|
|
349
|
+
* does, where Node resolves it from. Where the run added RTL to the nearest package declaring
|
|
350
|
+
* Enzyme, one of the `landed` package roots, it is there for every package within it.
|
|
96
351
|
*/
|
|
97
|
-
export function reactMajor(packages: Packages, sourcePath: string,
|
|
98
|
-
return compatibility(packages, sourcePath,
|
|
352
|
+
export function reactMajor(packages: Packages, sourcePath: string, landed: ReadonlySet<string> = new Set()): number {
|
|
353
|
+
return compatibility(packages, sourcePath, landed).react;
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** The events `simulate` can dispatch as `fireEvent` in a source file, and whether its render must be attached to the document for them. */
|
|
357
|
+
export interface SimulatedEvents {
|
|
358
|
+
events: ReadonlySet<string>;
|
|
359
|
+
attached: boolean;
|
|
99
360
|
}
|
|
100
361
|
|
|
362
|
+
// React 16 makes `onMouseEnter` and `onMouseLeave` of `mouseover` and `mouseout`, so a dispatched hover event
|
|
363
|
+
// runs the handlers of its pair as well, which `simulate` does not
|
|
364
|
+
const HOVER_EVENTS = new Set(["mouseEnter", "mouseLeave", "mouseOver", "mouseOut"]);
|
|
365
|
+
|
|
101
366
|
/**
|
|
102
|
-
*
|
|
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.
|
|
367
|
+
* Which `simulate` calls can become `fireEvent` for a source file. On React 17, every supported event,
|
|
368
|
+
* with an RTL whose `fireEvent.focus`, `blur`, `mouseEnter`, and `mouseLeave` also dispatch the events React 17
|
|
369
|
+
* listens to, which RTL 10 does only from 10.4.9. On React 16.9+, which listens on the document rather than
|
|
370
|
+
* the root, every one but the hover events, in a render attached to the document.
|
|
105
371
|
*/
|
|
106
|
-
export function simulatesEvents(packages: Packages, sourcePath: string,
|
|
107
|
-
const {react, rtl} = compatibility(packages, sourcePath,
|
|
108
|
-
|
|
372
|
+
export function simulatesEvents(packages: Packages, sourcePath: string, landed: ReadonlySet<string> = new Set()): SimulatedEvents {
|
|
373
|
+
const {react, rtl} = compatibility(packages, sourcePath, landed);
|
|
374
|
+
// React 18 listens on the root, as React 17 does
|
|
375
|
+
if (react >= 17 && rtl >= 11) return {events: SIMULATED_EVENTS, attached: false};
|
|
376
|
+
if (react === 16 && rtl >= 10) return {events: new Set([...SIMULATED_EVENTS].filter(event => !HOVER_EVENTS.has(event))), attached: true};
|
|
377
|
+
return {events: new Set(), attached: false};
|
|
109
378
|
}
|
|
110
379
|
|
|
111
380
|
/** 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,
|
|
381
|
+
function compatibility(packages: Packages, sourcePath: string, landed: ReadonlySet<string>): {react: number, rtl: number} {
|
|
113
382
|
const roots = [...packages.keys()].filter(root => sourcePath.startsWith(root)).sort((a, b) => b.length - a.length);
|
|
114
383
|
const declared = (name: "react" | "reactDom" | "rtl", from = roots) =>
|
|
115
384
|
from.map(root => packages.get(root)![name]).find(version => version !== undefined);
|
|
116
385
|
const supportedReact = (version: Declaration): version is DeclaredVersion => typeof version === "object" &&
|
|
117
|
-
(version.major === 17 || (version.major === 16 && version.minor !== undefined && version.minor >= 9));
|
|
386
|
+
(version.major === 17 || version.major === 18 || (version.major === 16 && version.minor !== undefined && version.minor >= 9));
|
|
118
387
|
const react = declared("react");
|
|
119
388
|
const rtl = declared("rtl");
|
|
120
389
|
const enzyme = roots.findIndex(root => packages.get(root)!.enzyme);
|
|
121
|
-
const
|
|
122
|
-
|
|
390
|
+
const enzymeReact = enzyme >= 0 ? declared("react", roots.slice(enzyme)) : undefined;
|
|
391
|
+
const added = rtl === undefined && enzyme >= 0 && landed.has(roots[enzyme]) &&
|
|
392
|
+
supportedReact(enzymeReact) && supportedReact(declared("reactDom", roots.slice(enzyme)));
|
|
123
393
|
// RTL renders with the React DOM it resolves from its own package
|
|
124
394
|
const rtlRoot = added ? enzyme : roots.findIndex(root => packages.get(root)!.rtl !== undefined);
|
|
125
395
|
const reactDom = declared("reactDom", roots.slice(Math.max(rtlRoot, 0))) ?? declared("reactDom");
|
|
126
396
|
// `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 <=
|
|
128
|
-
const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major &&
|
|
397
|
+
const rtlMajor = added ? ((enzymeReact as DeclaredVersion).major >= 18 ? 16 : 12) : typeof rtl === "object" && rtl.major >= 10 && rtl.major <= 16 ? rtl.major : 0;
|
|
398
|
+
const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major &&
|
|
399
|
+
rtlMajor > 0 && rtlSupports(rtlMajor, react.major);
|
|
129
400
|
return {react: compatible ? react.major : 0, rtl: rtlMajor};
|
|
130
401
|
}
|
|
131
402
|
|
|
403
|
+
/**
|
|
404
|
+
* Whether an RTL major renders with a React major as the runtime tests show: RTL 10 to 12 with React 16 and 17,
|
|
405
|
+
* and RTL 16 with React 18, where RTL 13 to 15 also render but are not covered.
|
|
406
|
+
*/
|
|
407
|
+
function rtlSupports(rtl: number, react: number): boolean {
|
|
408
|
+
return react <= 17 ? rtl <= 12 : rtl === 16;
|
|
409
|
+
}
|
|
410
|
+
|
|
132
411
|
/**
|
|
133
412
|
* A version or a range within a single major: `16.14.0`, `^16.14`, `~16.9.0`, `16.9.x`, or `^17`,
|
|
134
413
|
* whose minor version is known only where it is a lower bound.
|
|
@@ -146,15 +425,30 @@ function declaredVersion(version: string | undefined): Declaration {
|
|
|
146
425
|
* `mount(<Button />).find('button').length` and `const wrapper = mount(<Button />)` declarations
|
|
147
426
|
* whose every reference is a supported DOM read become RTL renders into a detached container.
|
|
148
427
|
*
|
|
428
|
+
* A `shallow` wrapper converts the same way where the full render cannot differ from the shallow
|
|
429
|
+
* one: its component, scanned from the source it is imported from, creates host elements only and
|
|
430
|
+
* runs no effects, and receives no component element from the test. `simulate` and `html()` stay
|
|
431
|
+
* excluded there, since a shallow render calls a handler without bubbling and prints static markup.
|
|
432
|
+
*
|
|
433
|
+
* ```tsx
|
|
434
|
+
* // before, where `Label` renders `<ul><li>{text}</li></ul>`
|
|
435
|
+
* const wrapper = shallow(<Label text="a" />);
|
|
436
|
+
* expect(wrapper.find('li').length).toBe(1);
|
|
437
|
+
* // after
|
|
438
|
+
* const wrapper = render(<Label text="a" />, {container: document.createElement('div')});
|
|
439
|
+
* expect(wrapper.container.querySelectorAll('li').length).toBe(1);
|
|
440
|
+
* ```
|
|
441
|
+
*
|
|
149
442
|
* Existing compatible RTL installation and DOM test setup are prerequisites. More complex
|
|
150
443
|
* wrapper flows remain in the inventory rather than being guessed at.
|
|
151
444
|
*
|
|
152
445
|
* @see https://testing-library.com/docs/react-testing-library/migrate-from-enzyme/#how-to-migrate-from-enzyme-to-react-testing-library
|
|
153
446
|
*/
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
readonly
|
|
157
|
-
readonly
|
|
447
|
+
|
|
448
|
+
export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
449
|
+
readonly name: string = "org.openrewrite.react.migrate.enzyme-to-react-testing-library";
|
|
450
|
+
readonly displayName: string = "Migrate Enzyme to React Testing Library";
|
|
451
|
+
readonly description: string = "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 `simulate` with common mouse, keyboard, focus, form, and touch events, including `nativeEvent` mocks, on React 17 and 18 and, without the hover events and in a render attached to the document, on React 16.9+) 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 or React 18 with RTL 16, adding RTL 12, or RTL 16 with its peer `@testing-library/dom` 10, where it is missing. Converts `shallow` wrappers the same way, without `simulate` or `html()`, where the component is imported from a source in the repository that creates host elements only and runs no effects, so a full render produces the DOM the shallow render does. 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, snapshots, and shallow rendering of other components are left for review.";
|
|
158
452
|
|
|
159
453
|
@Option({
|
|
160
454
|
displayName: "Convert positions into untagged selector matches",
|
|
@@ -163,22 +457,50 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
|
163
457
|
})
|
|
164
458
|
untaggedSelectorPositions?: boolean;
|
|
165
459
|
|
|
460
|
+
// The editor reads where it added RTL, so this is the instance the run prepares as a child
|
|
461
|
+
private readonly forecast: ConversionForecast = {};
|
|
462
|
+
|
|
463
|
+
// PERF: the sources that import Enzyme, kept from the scan to the forecast in `generate`, as the dependency steps keep
|
|
464
|
+
// their manifests. Not in the accumulator, which the host keeps until the cycle ends; cleared once the forecast is made.
|
|
465
|
+
private readonly tests: JS.CompilationUnit[] = [];
|
|
466
|
+
private readonly dependencySteps = ADDS_RTL ? {rtl: new AddTestingLibraryReact(this.forecast), rtl18: new AddTestingLibraryReact18(this.forecast),
|
|
467
|
+
dom18: new AddTestingLibraryDom18(this.forecast)} : undefined;
|
|
468
|
+
|
|
166
469
|
constructor(options?: {untaggedSelectorPositions?: boolean}) {
|
|
167
470
|
super(options);
|
|
168
471
|
}
|
|
169
472
|
|
|
473
|
+
/** Whether snapshot assertions of a wrapper convert, recording a new snapshot of the DOM; see {@link EnzymeSnapshotsToReactTestingLibrary}. */
|
|
474
|
+
protected readonly snapshots: boolean = false;
|
|
475
|
+
|
|
170
476
|
private readonly usages = new DataTable<EnzymeUsageRow>(
|
|
171
477
|
ENZYME_USAGE_TABLE, "Enzyme migration inventory",
|
|
172
478
|
"Remaining Enzyme usages and migration actions. Module rows include references whose call types may be unavailable; they are not counts of test cases.",
|
|
173
479
|
EnzymeUsageRow
|
|
174
480
|
);
|
|
175
481
|
|
|
176
|
-
initialValue():
|
|
177
|
-
|
|
482
|
+
initialValue(): Scanned {
|
|
483
|
+
this.tests.length = 0;
|
|
484
|
+
return {packages: new Map(), components: new Map(), modules: new Map(), names: new Map()};
|
|
178
485
|
}
|
|
179
486
|
|
|
180
|
-
|
|
181
|
-
|
|
487
|
+
// The host may prepare the visitors before there is an accumulator, so it is read only while visiting
|
|
488
|
+
async scanner(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
489
|
+
const steps = this.dependencySteps;
|
|
490
|
+
const tests = this.tests;
|
|
491
|
+
let converting: Promise<ReadonlySet<string>> | undefined;
|
|
492
|
+
// PERF: a second pass of the editor over the sources that import Enzyme, once, for all three steps
|
|
493
|
+
this.forecast.converting = steps && (() => converting ??= this.dryRun(scanned, rtlLanded(steps.rtl.candidates(), steps.rtl18.candidates(), steps.dom18.candidates())));
|
|
494
|
+
const sources = new class extends JavaScriptVisitor<ExecutionContext> {
|
|
495
|
+
override async visitJsCompilationUnit(cu: JS.CompilationUnit): Promise<J | undefined> {
|
|
496
|
+
scanned.components.set(cu.sourcePath, hostComponentExports(cu));
|
|
497
|
+
scanned.modules.set(cu.sourcePath, moduleFacts(cu));
|
|
498
|
+
scanned.names.set(cu.sourcePath, selectorNames(cu));
|
|
499
|
+
if (importBindings(cu).some(({module}) => module === ENZYME)) tests.push(cu);
|
|
500
|
+
return cu;
|
|
501
|
+
}
|
|
502
|
+
}();
|
|
503
|
+
const manifests = new class extends JsonVisitor<ExecutionContext> {
|
|
182
504
|
override async visitDocument(doc: Json.Document, ctx: ExecutionContext): Promise<Json | undefined> {
|
|
183
505
|
if (!/(^|\/)package\.json$/.test(doc.sourcePath)) return doc;
|
|
184
506
|
const resolution = findNodeResolutionResult(doc);
|
|
@@ -195,49 +517,103 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
|
195
517
|
(!validRange(dependency!.versionConstraint) || satisfies(resolved.version, dependency!.versionConstraint))) return resolved.version;
|
|
196
518
|
return dependencies.find(dep => dep.name === name)?.versionConstraint;
|
|
197
519
|
};
|
|
198
|
-
packages.set(doc.sourcePath.slice(0, -"package.json".length), {
|
|
520
|
+
scanned.packages.set(doc.sourcePath.slice(0, -"package.json".length), {
|
|
199
521
|
react: declaredVersion(version("react")),
|
|
200
522
|
reactDom: declaredVersion(version("react-dom")),
|
|
201
523
|
rtl: declaredVersion(version(RTL)),
|
|
202
524
|
enzyme: dependencies.some(dep => dep.name === "enzyme"),
|
|
203
|
-
|
|
525
|
+
dependencies: new Set(dependencies.map(dep => dep.name)),
|
|
526
|
+
rootStyles: (resolution?.resolvedDependencies ?? []).some(dep => {
|
|
527
|
+
const range = ROOT_STYLES.get(dep.name);
|
|
528
|
+
return range !== undefined && valid(dep.version) !== null && satisfies(dep.version, range);
|
|
529
|
+
})
|
|
204
530
|
});
|
|
205
531
|
return doc;
|
|
206
532
|
}
|
|
207
533
|
}();
|
|
534
|
+
const scan = new class extends TreeVisitor<any, ExecutionContext> {
|
|
535
|
+
override async isAcceptable(sourceFile: SourceFile): Promise<boolean> {
|
|
536
|
+
return await manifests.isAcceptable(sourceFile) || await sources.isAcceptable(sourceFile);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
|
|
540
|
+
if (tree.kind === Json.Kind.Document) return await manifests.visit(tree, ctx, parent) as R | undefined;
|
|
541
|
+
return tree.kind === JS.Kind.CompilationUnit ? await sources.visit(tree, ctx, parent) as R | undefined : tree as R;
|
|
542
|
+
}
|
|
543
|
+
}();
|
|
544
|
+
// HACK: the host infers which trees to send only from a JsonVisitor or JavaScriptVisitor, and sends a
|
|
545
|
+
// plain TreeVisitor every tree, including Python ones the TypeScript side has no codec for
|
|
546
|
+
return check(or(treesOfType("org.openrewrite.json.tree.Json"), treesOfType("org.openrewrite.javascript.tree.JS")), scan);
|
|
208
547
|
}
|
|
209
548
|
|
|
210
|
-
async editorWithData(
|
|
549
|
+
async editorWithData(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
550
|
+
return this.conversionEditor(scanned);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** The sources the editor converts where RTL lands in every package root of `landed`, recording no rows. */
|
|
554
|
+
private async dryRun(scanned: Scanned, landed: ReadonlySet<string>): Promise<ReadonlySet<string>> {
|
|
555
|
+
const dry: DryRun = {landed, converted: new Set()};
|
|
556
|
+
const editor = await this.conversionEditor(scanned, dry);
|
|
557
|
+
const ctx = new ExecutionContext();
|
|
558
|
+
for (const cu of this.tests) await editor.visit(cu, ctx);
|
|
559
|
+
this.tests.length = 0;
|
|
560
|
+
return dry.converted;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
private async conversionEditor(scanned: Scanned, dry?: DryRun): Promise<TreeVisitor<any, ExecutionContext>> {
|
|
211
564
|
const jsx = capture<Expression>({name: "element", constraint: node => node.kind !== JS.Kind.Spread});
|
|
212
|
-
const
|
|
213
|
-
const
|
|
565
|
+
const hostNames = (names: readonly string[]) => hostOnlyNames(names, scanned.names);
|
|
566
|
+
const selector = capture<J.Literal>({name: "selector", constraint: node => selectorLiteral(node, hostNames)});
|
|
214
567
|
const after = {context: [`import {render} from "${RTL}";`], dependencies: {[RTL]: "12.1.5", "@types/react": "16.14.62"}};
|
|
215
|
-
const
|
|
216
|
-
before:
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
}
|
|
223
|
-
const
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
568
|
+
const patterns = (api: Render) => {
|
|
569
|
+
const before = {lenientTypeMatching: false, context: [`import {${api}} from "enzyme";`], dependencies: {"@types/enzyme": "3.10.19", "@types/react": "16.14.62"}};
|
|
570
|
+
return {
|
|
571
|
+
render: pattern`${raw(api)}(${jsx})`.configure(before),
|
|
572
|
+
length: pattern`${raw(api)}(${jsx}).find(${selector}).length`.configure(before),
|
|
573
|
+
exists: pattern`${raw(api)}(${jsx}).find(${selector}).exists()`.configure(before)
|
|
574
|
+
};
|
|
575
|
+
};
|
|
576
|
+
const renderPatterns = {mount: patterns("mount"), shallow: patterns("shallow")};
|
|
577
|
+
const renderRules = (document: DocumentReference, api: Render) => {
|
|
578
|
+
const options = raw(renderOptions(document));
|
|
579
|
+
const from = renderPatterns[api];
|
|
580
|
+
return {
|
|
581
|
+
length: rewrite(() => ({
|
|
582
|
+
before: from.length,
|
|
583
|
+
after: template`render(${jsx}, ${options}).container.querySelectorAll(${selector}).length`.configure(after)
|
|
584
|
+
})),
|
|
585
|
+
exists: rewrite(() => ({
|
|
586
|
+
before: from.exists,
|
|
587
|
+
after: template`render(${jsx}, ${options}).container.querySelectorAll(${selector}).length > 0`.configure(after)
|
|
588
|
+
})),
|
|
589
|
+
mount: rewrite(() => ({
|
|
590
|
+
before: from.render,
|
|
591
|
+
after: template`render(${jsx}, ${options})`.configure(after)
|
|
592
|
+
})),
|
|
593
|
+
attachedMount: rewrite(() => ({
|
|
594
|
+
before: from.render,
|
|
595
|
+
after: template`render(${jsx})`.configure(after)
|
|
596
|
+
}))
|
|
597
|
+
};
|
|
598
|
+
};
|
|
599
|
+
const rules = {
|
|
600
|
+
"document": {mount: renderRules("document", "mount"), shallow: renderRules("document", "shallow")},
|
|
601
|
+
"globalThis.document": {mount: renderRules("globalThis.document", "mount"), shallow: renderRules("globalThis.document", "shallow")}
|
|
602
|
+
};
|
|
232
603
|
const usages = this.usages;
|
|
604
|
+
const steps = this.dependencySteps;
|
|
233
605
|
const untaggedPositions = this.untaggedSelectorPositions !== false;
|
|
234
|
-
|
|
606
|
+
const snapshots = this.snapshots;
|
|
607
|
+
return check(and(not(isVendoredOrBundled()), or(usesMethod("enzyme mount(..)"), usesMethod("enzyme shallow(..)"))), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
235
608
|
private enabled = false;
|
|
236
609
|
private reactMajor = 0;
|
|
237
|
-
private events = false;
|
|
610
|
+
private events: SimulatedEvents = {events: new Set(), attached: false};
|
|
611
|
+
private rootStyles = false;
|
|
238
612
|
private typescript = false;
|
|
239
613
|
private sourcePath = "";
|
|
240
|
-
private readonly mounts = new
|
|
614
|
+
private readonly mounts = new Map<string, ConvertedRender>();
|
|
615
|
+
private imports: ReadonlyMap<string, ImportedExport> = new Map();
|
|
616
|
+
private importedNames: ReadonlySet<string> = new Set();
|
|
241
617
|
private readonly uses = new Map<string, WrapperRead>();
|
|
242
618
|
private readonly removedStatements = new Set<string>();
|
|
243
619
|
private readonly unmounts = new Set<string>();
|
|
@@ -247,6 +623,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
|
247
623
|
private readonly hoists = new Map<string, HoistedElement>();
|
|
248
624
|
private readonly hoistedMounts = new Map<string, string>();
|
|
249
625
|
private names: ReadonlySet<string> = new Set();
|
|
626
|
+
private cu?: JS.CompilationUnit;
|
|
627
|
+
private readonly portals = new Set<string>();
|
|
250
628
|
private readonly rows: EnzymeUsageRow[] = [];
|
|
251
629
|
private prettier = false;
|
|
252
630
|
private printWidth = 80;
|
|
@@ -259,27 +637,55 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
|
259
637
|
this.rows.length = 0;
|
|
260
638
|
this.names = namesUsedIn(cu);
|
|
261
639
|
const prettierStyle = findMarker<PrettierStyle>(cu, StyleKind.PrettierStyle);
|
|
262
|
-
this.prettier = prettierStyle !== undefined;
|
|
640
|
+
this.prettier = prettierStyle !== undefined && !prettierStyle.ignored && await formattedBy(cu, prettierStyle);
|
|
263
641
|
this.printWidth = typeof prettierStyle?.config.printWidth === "number" ? prettierStyle.config.printWidth : 80;
|
|
264
|
-
|
|
265
|
-
this.
|
|
266
|
-
this.
|
|
642
|
+
const landed = dry ? dry.landed : steps ? rtlLanded(steps.rtl.landed, steps.rtl18.landed, steps.dom18.landed) : undefined;
|
|
643
|
+
this.reactMajor = reactMajor(scanned.packages, cu.sourcePath, landed);
|
|
644
|
+
this.events = simulatesEvents(scanned.packages, cu.sourcePath, landed);
|
|
645
|
+
this.rootStyles = injectsRootStyles(scanned.packages, cu.sourcePath);
|
|
646
|
+
this.typescript = isTypeScript(cu);
|
|
267
647
|
this.enabled = this.reactMajor > 0 && moduleBindings(this).moduleSystem === "esm";
|
|
268
|
-
if (!this.enabled
|
|
269
|
-
|
|
270
|
-
this.
|
|
271
|
-
|
|
648
|
+
if (!this.enabled) return cu;
|
|
649
|
+
this.imports = relativeImports(cu, scanned.components);
|
|
650
|
+
this.importedNames = importedNames(cu);
|
|
651
|
+
// Templates lay out what they insert with the source's Prettier style, which a source its config does not lay out keeps out of
|
|
652
|
+
const foreign = prettierStyle !== undefined && !this.prettier;
|
|
653
|
+
const visiting = foreign ? create(cu, draft => {
|
|
654
|
+
draft.markers.markers = draft.markers.markers.filter(marker => marker.kind !== StyleKind.PrettierStyle);
|
|
655
|
+
}) : cu;
|
|
656
|
+
// Templates find the style through the cursor, which `visit` set to the source as it came
|
|
657
|
+
if (foreign) this.cursor = new Cursor(visiting, this.cursor.parent);
|
|
658
|
+
this.cu = cu;
|
|
659
|
+
this.portals.clear();
|
|
660
|
+
const visited = await super.visitJsCompilationUnit(visiting, ctx);
|
|
661
|
+
if (dry) {
|
|
662
|
+
if (this.rows.some(row => row.status === "CONVERTED")) dry.converted.add(cu.sourcePath);
|
|
663
|
+
} else this.rows.forEach(row => usages.insertRow(ctx, row));
|
|
664
|
+
if (!foreign || !visited) return visited;
|
|
665
|
+
return visited === visiting ? cu : create(visited as JS.CompilationUnit, draft => {
|
|
666
|
+
draft.markers.markers.push(prettierStyle as any);
|
|
667
|
+
});
|
|
272
668
|
}
|
|
273
669
|
|
|
274
670
|
override async visitBlock(block: J.Block, ctx: ExecutionContext): Promise<J | undefined> {
|
|
275
671
|
const planned: string[] = [];
|
|
276
|
-
|
|
672
|
+
const apis: Render[] = [];
|
|
277
673
|
for (const statement of block.statements) {
|
|
278
|
-
const candidate = wrapperDeclaration(statement.element);
|
|
674
|
+
const candidate = wrapperDeclaration(statement.element, render => this.renderOf(render));
|
|
279
675
|
if (!candidate) continue;
|
|
280
|
-
const
|
|
281
|
-
|
|
282
|
-
this.
|
|
676
|
+
const api = candidate.render;
|
|
677
|
+
const reads = READS[api];
|
|
678
|
+
const scope = analyzeWrapperScope(this.cursor, candidate, {events: reads.simulate ? this.events.events : new Set(), html: reads.html, untaggedPositions, hostNames, snapshots,
|
|
679
|
+
constant: node => this.constantString(node)});
|
|
680
|
+
if (!scope) continue;
|
|
681
|
+
if ([...scope.uses.values()].some(use => use.use === "setProps" && !reads.props(use.props!, this.importedNames))) continue;
|
|
682
|
+
const mount = new Cursor(candidate.mount, variableCursor(this.cursor, candidate.declaration));
|
|
683
|
+
const document = documentAt(mount);
|
|
684
|
+
if (!document || !await renderPatterns[api].render.match(candidate.mount, mount)) continue;
|
|
685
|
+
const attached = this.events.attached && [...scope.uses.values()].some(use => use.use === "simulate");
|
|
686
|
+
if (!attached && this.rootStyles && [...scope.uses.values()].some(use => CONTAINER_READS.has(use.use))) continue;
|
|
687
|
+
this.mounts.set(candidate.mount.id, {document, api, attached});
|
|
688
|
+
apis.push(api);
|
|
283
689
|
this.declarations.add(candidate.declaration.id);
|
|
284
690
|
scope.uses.forEach((use, id) => this.uses.set(id, use));
|
|
285
691
|
scope.removedStatements.forEach(id => this.removedStatements.add(id));
|
|
@@ -293,7 +699,6 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
|
293
699
|
this.hoistedMounts.set(candidate.mount.id, name);
|
|
294
700
|
}
|
|
295
701
|
planned.push(candidate.mount.id, ...scope.uses.keys());
|
|
296
|
-
scopes++;
|
|
297
702
|
}
|
|
298
703
|
planned.forEach(id => this.pending.add(id));
|
|
299
704
|
const queued = this.afterVisit.length;
|
|
@@ -304,12 +709,12 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
|
304
709
|
if (planned.some(id => this.pending.has(id))) {
|
|
305
710
|
this.afterVisit.length = queued;
|
|
306
711
|
this.rows.length = rows;
|
|
307
|
-
|
|
712
|
+
idsWithin(block, this.reformat).forEach(id => this.reformat.delete(id));
|
|
308
713
|
// Uses of a wrapper declared further out are rolled back too, which its block has to see
|
|
309
|
-
|
|
714
|
+
idsWithin(block, new Set([...this.mounts.keys(), ...this.uses.keys()])).forEach(id => this.pending.add(id));
|
|
310
715
|
return block;
|
|
311
716
|
}
|
|
312
|
-
|
|
717
|
+
apis.forEach(api => this.converted(api, enclosingScope(this.cursor), "WRAPPER_SCOPE"));
|
|
313
718
|
// Prettier lays out statements by their position in the block as it was parsed, before any is added or removed
|
|
314
719
|
const laidOut = await this.withPrettierLayout(visited, ctx);
|
|
315
720
|
const statements: J.Block["statements"][number][] = [];
|
|
@@ -356,7 +761,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
|
356
761
|
const statements: J.Block["statements"][number][] = [];
|
|
357
762
|
let formatted = false;
|
|
358
763
|
for (const statement of block.statements) {
|
|
359
|
-
const ids =
|
|
764
|
+
const ids = idsWithin(statement.element, this.reformat);
|
|
360
765
|
if (ids.length === 0) {
|
|
361
766
|
statements.push(statement);
|
|
362
767
|
continue;
|
|
@@ -379,15 +784,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
|
379
784
|
const use = this.uses.get(field.id);
|
|
380
785
|
if (use) return await this.apply(use, field, ctx) ?? field;
|
|
381
786
|
const visited = await super.visitFieldAccess(field, ctx) as J.FieldAccess;
|
|
382
|
-
|
|
383
|
-
|
|
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;
|
|
787
|
+
const lengthOf = visited.name.element.simpleName === "length" && simpleChain(visited) ? this.renderOf(innermostCall(visited)) : undefined;
|
|
788
|
+
return lengthOf && await this.tryInline(lengthOf, "length", visited, `${lengthOf}.find.length`, "<inline expression>", "INLINE_DOM_QUERY", ctx) || visited;
|
|
391
789
|
}
|
|
392
790
|
|
|
393
791
|
override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
|
|
@@ -395,47 +793,36 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
|
395
793
|
if (use) return await this.apply(use, method, ctx) ?? method;
|
|
396
794
|
if (this.unmounts.has(method.id)) return withoutEnzymeTypes(method, ctx);
|
|
397
795
|
const visited = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
|
|
398
|
-
|
|
796
|
+
const mounted = this.mounts.get(method.id);
|
|
797
|
+
if (mounted) {
|
|
399
798
|
const hoisted = this.hoistedMounts.get(method.id);
|
|
400
799
|
const result = hoisted ?
|
|
401
|
-
await this.applyTemplate(Template.builder().code(`render(${hoisted}, {
|
|
402
|
-
await
|
|
800
|
+
await this.applyTemplate(Template.builder().code(mounted.attached ? `render(${hoisted})` : `render(${hoisted}, ${renderOptions(mounted.document)})`).build().configure(after), visited) :
|
|
801
|
+
await rules[mounted.document][mounted.api][mounted.attached ? "attachedMount" : "mount"].tryOn(this.cursor, visited, {visitor: this});
|
|
403
802
|
if (!result) return visited;
|
|
404
803
|
this.pending.delete(method.id);
|
|
405
804
|
return withRenderOptionsOnElementLine(result, ctx);
|
|
406
805
|
}
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
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;
|
|
806
|
+
const statementOf = mountedElement(visited) && statementPosition(this.cursor) && !passesRef(visited) ? this.renderOf(visited, false) : undefined;
|
|
807
|
+
const statement = statementOf && await this.tryInline(statementOf, "mount", visited, statementOf, enclosingScope(this.cursor), "MOUNT_STATEMENT", ctx);
|
|
808
|
+
if (statement) return statement;
|
|
809
|
+
const existsOf = visited.name.simpleName === "exists" && simpleChain(visited) ? this.renderOf(innermostCall(visited)) : undefined;
|
|
810
|
+
return existsOf && await this.tryInline(existsOf, "exists", visited, `${existsOf}.find.exists`, "<inline expression>", "INLINE_DOM_QUERY", ctx) || visited;
|
|
424
811
|
}
|
|
425
812
|
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
return
|
|
813
|
+
/** Converts an inline render, read, or bare render statement with one of the rules, recording it as `api` in `scope`. */
|
|
814
|
+
private async tryInline(render: Render, rule: "length" | "exists" | "mount", node: J, api: string, scope: string, reason: string,
|
|
815
|
+
ctx: ExecutionContext): Promise<J | undefined> {
|
|
816
|
+
const document = documentAt(this.cursor);
|
|
817
|
+
const result = document && await rules[document][render][rule].tryOn(this.cursor, node, {visitor: this});
|
|
818
|
+
if (!result) return undefined;
|
|
819
|
+
this.converted(api, scope, reason);
|
|
820
|
+
this.laidOutByPrettier(result);
|
|
821
|
+
return withRenderOptionsOnElementLine(result, ctx);
|
|
435
822
|
}
|
|
436
823
|
|
|
437
824
|
private async apply(read: WrapperRead, node: J, ctx: ExecutionContext): Promise<J | undefined> {
|
|
438
|
-
const result = await this.applyTemplate(this.readTemplate(read
|
|
825
|
+
const result = await this.applyTemplate(this.readTemplate(read), node);
|
|
439
826
|
if (!result) return undefined;
|
|
440
827
|
this.pending.delete(node.id);
|
|
441
828
|
this.laidOutByPrettier(result);
|
|
@@ -450,7 +837,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
|
450
837
|
return replacement.apply(node, this.cursor, {bindings: await replacement.resolveBindings(this)});
|
|
451
838
|
}
|
|
452
839
|
|
|
453
|
-
private readTemplate(read: WrapperRead
|
|
840
|
+
private readTemplate(read: WrapperRead): Template {
|
|
454
841
|
const code = Template.builder();
|
|
455
842
|
const nodes = () => code.param(read.wrapper).code(".container.querySelectorAll(").param(read.selector!).code(")");
|
|
456
843
|
// Enzyme throws where a single-node method finds no node; so does a non-null element here
|
|
@@ -463,30 +850,22 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
|
463
850
|
if (read.index !== undefined && read.index !== "first") return nodes().code("[").param(read.index).code("]");
|
|
464
851
|
return code.param(read.wrapper).code(".container.querySelector(").param(read.selector!).code(")" + assertion);
|
|
465
852
|
};
|
|
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
853
|
// Enzyme finds nothing within a position it has no element at
|
|
473
854
|
const within = () => element(false).code("?.querySelectorAll(").param(read.within!).code(").length ?? 0");
|
|
474
855
|
switch (read.use) {
|
|
475
856
|
case "length":
|
|
476
|
-
if (read.within) return
|
|
857
|
+
if (read.within) return within().build();
|
|
477
858
|
return nodes().code(".length").build();
|
|
478
859
|
case "exists":
|
|
479
|
-
if (read.within)
|
|
860
|
+
if (read.within) {
|
|
480
861
|
code.code("(");
|
|
481
|
-
within().code(") > 0");
|
|
482
|
-
}
|
|
483
|
-
return
|
|
862
|
+
return within().code(") > 0").build();
|
|
863
|
+
}
|
|
864
|
+
return nodes().code(".length > 0").build();
|
|
484
865
|
case "positionExists":
|
|
485
|
-
return
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
else nodes().code("[").param(read.index!).code("] !== undefined");
|
|
489
|
-
});
|
|
866
|
+
if (read.index === "first") return code.param(read.wrapper).code(".container.querySelector(").param(read.selector!).code(") !== null").build();
|
|
867
|
+
if (read.index === "last") return nodes().code(".length > 0").build();
|
|
868
|
+
return nodes().code("[").param(read.index!).code("] !== undefined").build();
|
|
490
869
|
case "nodes":
|
|
491
870
|
return nodes().build();
|
|
492
871
|
// An element's text content is never null, though its type allows it
|
|
@@ -497,8 +876,15 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
|
497
876
|
return element(false).code("?.textContent").build();
|
|
498
877
|
case "html":
|
|
499
878
|
return element(!!read.unasserted).code(read.unasserted ? ".outerHTML" : "?.outerHTML").build();
|
|
879
|
+
case "rootHtml":
|
|
880
|
+
return code.param(read.wrapper).code(".container.innerHTML").build();
|
|
881
|
+
case "node":
|
|
882
|
+
return element(true).build();
|
|
500
883
|
case "hasClass":
|
|
501
884
|
return element(true).code(".classList.contains(").param(read.className!).code(")").build();
|
|
885
|
+
// RTL's fragment holds the rendered DOM, which Jest serializes in place of Enzyme's tree
|
|
886
|
+
case "snapshot":
|
|
887
|
+
return code.code("expect(").param(read.wrapper).code(".asFragment())").build();
|
|
502
888
|
case "setProps":
|
|
503
889
|
code.param(read.wrapper).code(`.rerender(${read.reassigned ? `(${read.element} = ` : ""}cloneElement(${read.element}, `);
|
|
504
890
|
return code.param(read.props!).code(read.reassigned ? ")))" : "))").build().configure({
|
|
@@ -528,11 +914,55 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
|
528
914
|
}
|
|
529
915
|
}
|
|
530
916
|
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
917
|
+
/**
|
|
918
|
+
* The Enzyme render a call is, where RTL's `render` renders the same DOM: a `mount`, unless its
|
|
919
|
+
* wrapper is `read` and a component it renders may render into a portal, and a `shallow` of a
|
|
920
|
+
* component that renders host elements only, as {@link rendersHostElements} decides.
|
|
921
|
+
*/
|
|
922
|
+
private renderOf(node: J | undefined, read = true): Render | undefined {
|
|
923
|
+
if (node?.kind !== J.Kind.MethodInvocation) return undefined;
|
|
924
|
+
const call = node as J.MethodInvocation;
|
|
925
|
+
const api = enzymeMethod(call);
|
|
926
|
+
if (api === "mount") return read && this.rendersPortal(call) ? undefined : api;
|
|
927
|
+
const element = call.arguments.elements[0]?.element;
|
|
928
|
+
return api === "shallow" && call.arguments.elements.length === 1 && rendersHostElements(element, this.imports, scanned.components, this.importedNames) ? api : undefined;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
/**
|
|
932
|
+
* Whether a component that a `mount` renders may render into a portal. Enzyme finds portal content
|
|
933
|
+
* in the wrapper, and RTL's container does not hold it, so a converted read would count none and
|
|
934
|
+
* an assertion of its absence would hold vacuously.
|
|
935
|
+
*/
|
|
936
|
+
private rendersPortal(call: J.MethodInvocation): boolean {
|
|
937
|
+
const element = call.arguments.elements[0]?.element;
|
|
938
|
+
const {roots, declares, resolve} = this.moduleResolution();
|
|
939
|
+
const portal = !!element && !!this.cu && rendersPortal(element, this.cu, {
|
|
940
|
+
sourcePath: this.sourcePath,
|
|
941
|
+
modules: scanned.modules,
|
|
942
|
+
resolve,
|
|
943
|
+
declares,
|
|
944
|
+
packagePortals: () => [...scanned.modules].some(([path, facts]) => facts.portal &&
|
|
945
|
+
path.startsWith(roots[0] ?? "") && !/(^|\/)__tests?__\/|\.(test|spec)\.[cm]?[jt]sx?$/.test(path))
|
|
946
|
+
});
|
|
947
|
+
if (portal && !this.portals.has(call.id)) {
|
|
948
|
+
this.portals.add(call.id);
|
|
949
|
+
this.rows.push({sourcePath: this.sourcePath, scope: enclosingScope(this.cursor), api: "mount", status: "REVIEW", reason: "PORTAL",
|
|
950
|
+
suggestedAction: "A component it renders may render into a portal, which RTL renders outside the container: query `screen` or `baseElement` for that content."});
|
|
951
|
+
}
|
|
952
|
+
return portal;
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
/** How the test's module specifiers resolve: from the packages enclosing it, as {@link resolver} does. */
|
|
956
|
+
private moduleResolution() {
|
|
957
|
+
const roots = [...scanned.packages.keys()].filter(root => this.sourcePath.startsWith(root)).sort((a, b) => b.length - a.length);
|
|
958
|
+
const declares = (name: string) => roots.some(root => scanned.packages.get(root)!.dependencies.has(name));
|
|
959
|
+
return {roots, declares, resolve: resolver(scanned.modules, [...new Set([...roots, ""])], declares)};
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
/** The string a template of `const` strings holds, from the test or the modules it imports them from. */
|
|
963
|
+
private constantString(node: J): string | undefined {
|
|
964
|
+
const parts = stringParts(node);
|
|
965
|
+
return parts && evaluate(parts, this.sourcePath, scanned.modules, this.moduleResolution().resolve);
|
|
536
966
|
}
|
|
537
967
|
|
|
538
968
|
private laidOutByPrettier(node: J): void {
|
|
@@ -541,6 +971,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
|
541
971
|
|
|
542
972
|
private converted(api: string, scope: string, reason: string): void {
|
|
543
973
|
maybeRemoveImport(this, ENZYME);
|
|
974
|
+
if (snapshots) maybeRemoveImport(this, "enzyme-to-json");
|
|
544
975
|
this.rows.push({sourcePath: this.sourcePath, scope, api, status: "CONVERTED", reason,
|
|
545
976
|
suggestedAction: "Run the migrated test and review whether an accessible RTL query would better express its intent."});
|
|
546
977
|
}
|
|
@@ -548,6 +979,19 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Packages> {
|
|
|
548
979
|
}
|
|
549
980
|
|
|
550
981
|
async recipeList() {
|
|
551
|
-
|
|
982
|
+
const steps = this.dependencySteps;
|
|
983
|
+
return [...steps ? [steps.rtl, steps.rtl18, steps.dom18] : [], new FindEnzymeUsage()];
|
|
552
984
|
}
|
|
553
985
|
}
|
|
986
|
+
|
|
987
|
+
/**
|
|
988
|
+
* {@link EnzymeToReactTestingLibrary}, also converting snapshot assertions of the wrappers it converts. RTL
|
|
989
|
+
* snapshots the rendered DOM, which Enzyme's serializer records as a component tree, so every converted
|
|
990
|
+
* snapshot is written anew on the next run with `--updateSnapshot` and should be reviewed then.
|
|
991
|
+
*/
|
|
992
|
+
export class EnzymeSnapshotsToReactTestingLibrary extends EnzymeToReactTestingLibrary {
|
|
993
|
+
override readonly name = "org.openrewrite.react.migrate.enzyme-snapshots-to-react-testing-library";
|
|
994
|
+
override readonly displayName = "Migrate Enzyme to React Testing Library, snapshots included";
|
|
995
|
+
override readonly description = "Migrates Enzyme wrappers as `org.openrewrite.react.migrate.enzyme-to-react-testing-library` does, and also converts `expect(wrapper).toMatchSnapshot()` and `expect(toJson(wrapper)).toMatchSnapshot()` of those wrappers to `expect(wrapper.asFragment()).toMatchSnapshot()`, removing the `enzyme-to-json` import where nothing else uses it. RTL snapshots the rendered DOM where Enzyme's serializer recorded a component tree, so the stored snapshots of converted tests no longer match: run the tests with `--updateSnapshot` once and review the new snapshots. Inline snapshots and snapshots of shallow renders that are not converted are left for review.";
|
|
996
|
+
protected override readonly snapshots: boolean = true;
|
|
997
|
+
}
|