@openrewrite/recipes-react 0.21.0 → 0.23.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 +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +27 -0
- package/dist/index.js.map +1 -1
- package/dist/migration/change-component-prop-value.d.ts.map +1 -1
- package/dist/migration/change-component-prop-value.js +14 -4
- package/dist/migration/change-component-prop-value.js.map +1 -1
- package/dist/mui/adapt-v4-theme.d.ts +8 -0
- package/dist/mui/adapt-v4-theme.d.ts.map +1 -0
- package/dist/mui/adapt-v4-theme.js +65 -0
- package/dist/mui/adapt-v4-theme.js.map +1 -0
- package/dist/mui/add-component-prop.d.ts +18 -0
- package/dist/mui/add-component-prop.d.ts.map +1 -0
- package/dist/mui/add-component-prop.js +53 -0
- package/dist/mui/add-component-prop.js.map +1 -0
- package/dist/mui/add-emotion-prepend.d.ts +8 -0
- package/dist/mui/add-emotion-prepend.d.ts.map +1 -0
- package/dist/mui/add-emotion-prepend.js +71 -0
- package/dist/mui/add-emotion-prepend.js.map +1 -0
- package/dist/mui/change-module-specifier.d.ts +14 -0
- package/dist/mui/change-module-specifier.d.ts.map +1 -0
- package/dist/mui/change-module-specifier.js +95 -0
- package/dist/mui/change-module-specifier.js.map +1 -0
- package/dist/mui/convert-mui-imports.d.ts +14 -0
- package/dist/mui/convert-mui-imports.d.ts.map +1 -0
- package/dist/mui/convert-mui-imports.js +195 -0
- package/dist/mui/convert-mui-imports.js.map +1 -0
- package/dist/mui/convert-prop-to-sx.d.ts +22 -0
- package/dist/mui/convert-prop-to-sx.d.ts.map +1 -0
- package/dist/mui/convert-prop-to-sx.js +99 -0
- package/dist/mui/convert-prop-to-sx.js.map +1 -0
- package/dist/mui/index.d.ts +32 -0
- package/dist/mui/index.d.ts.map +1 -0
- package/dist/mui/index.js +67 -0
- package/dist/mui/index.js.map +1 -0
- package/dist/mui/jsx-attributes.d.ts +27 -0
- package/dist/mui/jsx-attributes.d.ts.map +1 -0
- package/dist/mui/jsx-attributes.js +140 -0
- package/dist/mui/jsx-attributes.js.map +1 -0
- package/dist/mui/mark-manual-migration.d.ts +16 -0
- package/dist/mui/mark-manual-migration.d.ts.map +1 -0
- package/dist/mui/mark-manual-migration.js +73 -0
- package/dist/mui/mark-manual-migration.js.map +1 -0
- package/dist/mui/mark-palette-mode-usage.d.ts +12 -0
- package/dist/mui/mark-palette-mode-usage.d.ts.map +1 -0
- package/dist/mui/mark-palette-mode-usage.js +50 -0
- package/dist/mui/mark-palette-mode-usage.js.map +1 -0
- package/dist/mui/move-component-prop-to-slot.d.ts +22 -0
- package/dist/mui/move-component-prop-to-slot.d.ts.map +1 -0
- package/dist/mui/move-component-prop-to-slot.js +87 -0
- package/dist/mui/move-component-prop-to-slot.js.map +1 -0
- package/dist/mui/move-primary-text-to-children.d.ts +12 -0
- package/dist/mui/move-primary-text-to-children.d.ts.map +1 -0
- package/dist/mui/move-primary-text-to-children.js +52 -0
- package/dist/mui/move-primary-text-to-children.js.map +1 -0
- package/dist/mui/move-system-props-to-sx.d.ts +16 -0
- package/dist/mui/move-system-props-to-sx.d.ts.map +1 -0
- package/dist/mui/move-system-props-to-sx.js +122 -0
- package/dist/mui/move-system-props-to-sx.js.map +1 -0
- package/dist/mui/mui-components.d.ts +8 -0
- package/dist/mui/mui-components.d.ts.map +1 -0
- package/dist/mui/mui-components.js +41 -0
- package/dist/mui/mui-components.js.map +1 -0
- package/dist/mui/mui-tag-visitor.d.ts +5 -0
- package/dist/mui/mui-tag-visitor.d.ts.map +1 -0
- package/dist/mui/mui-tag-visitor.js +54 -0
- package/dist/mui/mui-tag-visitor.js.map +1 -0
- package/dist/mui/pre-v5-recipe.d.ts +14 -0
- package/dist/mui/pre-v5-recipe.d.ts.map +1 -0
- package/dist/mui/pre-v5-recipe.js +88 -0
- package/dist/mui/pre-v5-recipe.js.map +1 -0
- package/dist/mui/remove-component-prop.d.ts +18 -0
- package/dist/mui/remove-component-prop.d.ts.map +1 -0
- package/dist/mui/remove-component-prop.js +55 -0
- package/dist/mui/remove-component-prop.js.map +1 -0
- package/dist/mui/remove-root-ref.d.ts +8 -0
- package/dist/mui/remove-root-ref.d.ts.map +1 -0
- package/dist/mui/remove-root-ref.js +61 -0
- package/dist/mui/remove-root-ref.js.map +1 -0
- package/dist/mui/remove-spacing-px-suffix.d.ts +8 -0
- package/dist/mui/remove-spacing-px-suffix.d.ts.map +1 -0
- package/dist/mui/remove-spacing-px-suffix.js +62 -0
- package/dist/mui/remove-spacing-px-suffix.js.map +1 -0
- package/dist/mui/rename-component-prop.d.ts +20 -0
- package/dist/mui/rename-component-prop.d.ts.map +1 -0
- package/dist/mui/rename-component-prop.js +66 -0
- package/dist/mui/rename-component-prop.js.map +1 -0
- package/dist/mui/rename-joy-css-variables.d.ts +8 -0
- package/dist/mui/rename-joy-css-variables.d.ts.map +1 -0
- package/dist/mui/rename-joy-css-variables.js +51 -0
- package/dist/mui/rename-joy-css-variables.js.map +1 -0
- package/dist/mui/rename-theme-palette-type.d.ts +8 -0
- package/dist/mui/rename-theme-palette-type.d.ts.map +1 -0
- package/dist/mui/rename-theme-palette-type.js +61 -0
- package/dist/mui/rename-theme-palette-type.js.map +1 -0
- package/dist/mui/replace-box-border-radius.d.ts +10 -0
- package/dist/mui/replace-box-border-radius.d.ts.map +1 -0
- package/dist/mui/replace-box-border-radius.js +50 -0
- package/dist/mui/replace-box-border-radius.js.map +1 -0
- package/dist/mui/replace-breakpoints-width.d.ts +8 -0
- package/dist/mui/replace-breakpoints-width.d.ts.map +1 -0
- package/dist/mui/replace-breakpoints-width.js +46 -0
- package/dist/mui/replace-breakpoints-width.js.map +1 -0
- package/dist/mui/replace-component-class.d.ts +18 -0
- package/dist/mui/replace-component-class.d.ts.map +1 -0
- package/dist/mui/replace-component-class.js +126 -0
- package/dist/mui/replace-component-class.js.map +1 -0
- package/dist/mui/replace-components-with-slots.d.ts +14 -0
- package/dist/mui/replace-components-with-slots.d.ts.map +1 -0
- package/dist/mui/replace-components-with-slots.js +69 -0
- package/dist/mui/replace-components-with-slots.js.map +1 -0
- package/dist/mui/replace-import-paths.d.ts +14 -0
- package/dist/mui/replace-import-paths.d.ts.map +1 -0
- package/dist/mui/replace-import-paths.js +101 -0
- package/dist/mui/replace-import-paths.js.map +1 -0
- package/dist/mui/replace-in-string-literals.d.ts +15 -0
- package/dist/mui/replace-in-string-literals.d.ts.map +1 -0
- package/dist/mui/replace-in-string-literals.js +62 -0
- package/dist/mui/replace-in-string-literals.js.map +1 -0
- package/dist/mui/replace-list-item-button-prop.d.ts +12 -0
- package/dist/mui/replace-list-item-button-prop.d.ts.map +1 -0
- package/dist/mui/replace-list-item-button-prop.js +80 -0
- package/dist/mui/replace-list-item-button-prop.js.map +1 -0
- package/dist/mui/replace-tabs-scroll-buttons.d.ts +8 -0
- package/dist/mui/replace-tabs-scroll-buttons.d.ts.map +1 -0
- package/dist/mui/replace-tabs-scroll-buttons.js +41 -0
- package/dist/mui/replace-tabs-scroll-buttons.js.map +1 -0
- package/dist/mui/replace-theme-color-functions.d.ts +8 -0
- package/dist/mui/replace-theme-color-functions.d.ts.map +1 -0
- package/dist/mui/replace-theme-color-functions.js +72 -0
- package/dist/mui/replace-theme-color-functions.js.map +1 -0
- package/dist/mui/replace-theme-spacing-unit.d.ts +8 -0
- package/dist/mui/replace-theme-spacing-unit.d.ts.map +1 -0
- package/dist/mui/replace-theme-spacing-unit.js +77 -0
- package/dist/mui/replace-theme-spacing-unit.js.map +1 -0
- package/dist/mui/replace-typography-round.d.ts +8 -0
- package/dist/mui/replace-typography-round.d.ts.map +1 -0
- package/dist/mui/replace-typography-round.js +44 -0
- package/dist/mui/replace-typography-round.js.map +1 -0
- package/dist/mui/shift-hidden-down-props.d.ts +10 -0
- package/dist/mui/shift-hidden-down-props.d.ts.map +1 -0
- package/dist/mui/shift-hidden-down-props.js +49 -0
- package/dist/mui/shift-hidden-down-props.js.map +1 -0
- package/dist/mui/theme-access.d.ts +5 -0
- package/dist/mui/theme-access.d.ts.map +1 -0
- package/dist/mui/theme-access.js +21 -0
- package/dist/mui/theme-access.js.map +1 -0
- package/dist/mui/update-theme-breakpoints.d.ts +10 -0
- package/dist/mui/update-theme-breakpoints.d.ts.map +1 -0
- package/dist/mui/update-theme-breakpoints.js +58 -0
- package/dist/mui/update-theme-breakpoints.js.map +1 -0
- package/dist/mui/upgrade-grid-props.d.ts +16 -0
- package/dist/mui/upgrade-grid-props.d.ts.map +1 -0
- package/dist/mui/upgrade-grid-props.js +90 -0
- package/dist/mui/upgrade-grid-props.js.map +1 -0
- package/dist/react19/use-context-hook.d.ts.map +1 -1
- package/dist/react19/use-context-hook.js +2 -0
- package/dist/react19/use-context-hook.js.map +1 -1
- package/dist/search/find-enzyme-usage.d.ts +4 -0
- package/dist/search/find-enzyme-usage.d.ts.map +1 -1
- package/dist/search/find-enzyme-usage.js +91 -7
- package/dist/search/find-enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-host-components.d.ts +12 -0
- package/dist/testing/enzyme-host-components.d.ts.map +1 -1
- package/dist/testing/enzyme-host-components.js +100 -0
- package/dist/testing/enzyme-host-components.js.map +1 -1
- package/dist/testing/enzyme-render-blockers.d.ts +13 -4
- package/dist/testing/enzyme-render-blockers.d.ts.map +1 -1
- package/dist/testing/enzyme-render-blockers.js +162 -6
- package/dist/testing/enzyme-render-blockers.js.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.d.ts +9 -2
- package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
- package/dist/testing/enzyme-to-react-testing-library.js +163 -16
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-usage.d.ts +7 -0
- package/dist/testing/enzyme-usage.d.ts.map +1 -1
- package/dist/testing/enzyme-usage.js +8 -1
- package/dist/testing/enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +8 -5
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +16 -4
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
- package/dist/zustand/redux-stores.d.ts +2 -0
- package/dist/zustand/redux-stores.d.ts.map +1 -1
- package/dist/zustand/redux-stores.js +120 -6
- package/dist/zustand/redux-stores.js.map +1 -1
- package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
- package/dist/zustand/redux-to-zustand.js +10 -4
- package/dist/zustand/redux-to-zustand.js.map +1 -1
- package/dist/zustand/zustand-plan.d.ts +7 -0
- package/dist/zustand/zustand-plan.d.ts.map +1 -1
- package/dist/zustand/zustand-plan.js +141 -21
- package/dist/zustand/zustand-plan.js.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +10 -0
- package/src/migration/change-component-prop-value.ts +19 -8
- package/src/mui/adapt-v4-theme.ts +43 -0
- package/src/mui/add-component-prop.ts +43 -0
- package/src/mui/add-emotion-prepend.ts +48 -0
- package/src/mui/change-module-specifier.ts +71 -0
- package/src/mui/convert-mui-imports.ts +184 -0
- package/src/mui/convert-prop-to-sx.ts +89 -0
- package/src/mui/index.ts +31 -0
- package/src/mui/jsx-attributes.ts +133 -0
- package/src/mui/mark-manual-migration.ts +53 -0
- package/src/mui/mark-palette-mode-usage.ts +36 -0
- package/src/mui/move-component-prop-to-slot.ts +84 -0
- package/src/mui/move-primary-text-to-children.ts +41 -0
- package/src/mui/move-system-props-to-sx.ts +118 -0
- package/src/mui/mui-components.ts +40 -0
- package/src/mui/mui-tag-visitor.ts +36 -0
- package/src/mui/pre-v5-recipe.ts +82 -0
- package/src/mui/remove-component-prop.ts +43 -0
- package/src/mui/remove-root-ref.ts +41 -0
- package/src/mui/remove-spacing-px-suffix.ts +43 -0
- package/src/mui/rename-component-prop.ts +55 -0
- package/src/mui/rename-joy-css-variables.ts +41 -0
- package/src/mui/rename-theme-palette-type.ts +42 -0
- package/src/mui/replace-box-border-radius.ts +42 -0
- package/src/mui/replace-breakpoints-width.ts +28 -0
- package/src/mui/replace-component-class.ts +97 -0
- package/src/mui/replace-components-with-slots.ts +61 -0
- package/src/mui/replace-import-paths.ts +100 -0
- package/src/mui/replace-in-string-literals.ts +44 -0
- package/src/mui/replace-list-item-button-prop.ts +59 -0
- package/src/mui/replace-tabs-scroll-buttons.ts +31 -0
- package/src/mui/replace-theme-color-functions.ts +55 -0
- package/src/mui/replace-theme-spacing-unit.ts +59 -0
- package/src/mui/replace-typography-round.ts +29 -0
- package/src/mui/shift-hidden-down-props.ts +44 -0
- package/src/mui/theme-access.ts +18 -0
- package/src/mui/update-theme-breakpoints.ts +47 -0
- package/src/mui/upgrade-grid-props.ts +82 -0
- package/src/react19/use-context-hook.ts +2 -0
- package/src/search/find-enzyme-usage.ts +80 -7
- package/src/testing/enzyme-host-components.ts +110 -0
- package/src/testing/enzyme-render-blockers.ts +174 -9
- package/src/testing/enzyme-to-react-testing-library.ts +159 -25
- package/src/testing/enzyme-usage.ts +13 -0
- package/src/testing/enzyme-wrapper-scope.ts +27 -6
- package/src/zustand/redux-stores.ts +119 -5
- package/src/zustand/redux-to-zustand.ts +12 -5
- package/src/zustand/zustand-plan.ts +159 -18
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import {Cursor, TreePrinters} from "@openrewrite/rewrite";
|
|
2
2
|
import {JS} from "@openrewrite/rewrite/javascript";
|
|
3
|
-
import {J} from "@openrewrite/rewrite/java";
|
|
3
|
+
import {isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
4
4
|
import {eventKind, selectorKind} from "../search/find-enzyme-usage";
|
|
5
5
|
import {migrationReason} from "./enzyme-usage";
|
|
6
|
+
import type {BlockingReference} from "./enzyme-wrapper-scope";
|
|
7
|
+
import type {ShallowMiss} from "./enzyme-host-components";
|
|
6
8
|
|
|
7
9
|
/** Why the converter kept a render it analyzed on Enzyme, other than a use of its wrapper. */
|
|
8
10
|
export type RenderGate = "setProps" | "rootStyles" | "shallow" | "portal";
|
|
@@ -24,6 +26,10 @@ const PASSED = "Blocked by a wrapper passed on: the recipe converts a wrapper on
|
|
|
24
26
|
"Inline what the helper reads here, or change the helper to take the element RTL queried, such as `container.querySelector(selector)`.";
|
|
25
27
|
const STORED = "Blocked by a stored find: Enzyme's found wrapper keeps the render as it was, while an RTL element is live. " +
|
|
26
28
|
"Query the element where each assertion reads it, such as `container.querySelector(selector)`, rather than keeping the found wrapper in a variable.";
|
|
29
|
+
const SNAPSHOT_RECIPE = "`org.openrewrite.react.migrate.enzyme-snapshots-to-react-testing-library`";
|
|
30
|
+
const SNAPSHOT_AFTER = "RTL records the DOM where Enzyme recorded a component tree, so run the tests once with `--updateSnapshot` and review the new snapshots.";
|
|
31
|
+
const SNAPSHOT = `Blocked by a snapshot of the wrapper, which this recipe leaves for review: ${SNAPSHOT_RECIPE} converts it to \`expect(asFragment()).toMatchSnapshot()\`. ` +
|
|
32
|
+
`Run that recipe instead. ${SNAPSHOT_AFTER}`;
|
|
27
33
|
const UNMOUNTED = "Blocked by a read after unmount: RTL's container is empty once the render unmounts. " +
|
|
28
34
|
"Assert before calling `unmount()`, or render again for what comes after.";
|
|
29
35
|
const FIND_HERE = "Blocked by `find`: Enzyme and the DOM can match different elements for this selector where it stands, " +
|
|
@@ -43,6 +49,28 @@ const GATES: Readonly<Record<RenderGate, string>> = {
|
|
|
43
49
|
"Render without the `container` option, so the render is attached to the document, before reading text or markup."
|
|
44
50
|
};
|
|
45
51
|
|
|
52
|
+
const SHALLOW_MISSES: Readonly<Record<ShallowMiss["kind"], [string, string]>> = {
|
|
53
|
+
child: ["a child component", "`shallow` leaves each child component unrendered, and RTL's `render` renders it in full. " +
|
|
54
|
+
"Render it with `render` and assert on what the child renders, such as its text or role. Where a test relies on the child not rendering, `jest.mock` its module with a stub."],
|
|
55
|
+
effect: ["an effect or ref", "`shallow` runs no effect and attaches no ref, and RTL's `render` does both. " +
|
|
56
|
+
"Render it with `render`, and mock what the effect calls where a test relies on it not running."],
|
|
57
|
+
hook: ["a hook from outside React", "the hook may run effects, which `shallow` doesn't run and RTL's `render` does. " +
|
|
58
|
+
"Render it with `render`, and `jest.mock` the hook's module where a test relies on its effects not running."],
|
|
59
|
+
wrapped: ["a wrapped component", "`shallow` renders only the wrapper's output, and RTL's `render` renders through it. " +
|
|
60
|
+
"Render it with `render` and assert on what the inner component renders, wrapping it in what the wrapper needs, such as a store or theme provider."],
|
|
61
|
+
package: ["a component the recipe can't read", "it may render other components or run effects, which `shallow` leaves out and RTL's `render` runs. " +
|
|
62
|
+
"Render it with `render` and assert on what the whole tree renders."],
|
|
63
|
+
passed: ["an element passed in", "`shallow` leaves an element of a component in the props or children unrendered, and RTL's `render` renders it in full. " +
|
|
64
|
+
"Render it with `render` and assert on what that element renders, or pass a host element, such as a `<div>`, where a test needs only a placeholder."]
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
/** The suggested action for a `shallow` the recipe keeps, naming what it leaves out where that is known. */
|
|
68
|
+
export function blockedByShallow(miss: ShallowMiss | undefined): string {
|
|
69
|
+
if (!miss) return GATES.shallow;
|
|
70
|
+
const [what, why] = SHALLOW_MISSES[miss.kind];
|
|
71
|
+
return `Blocked by shallow rendering of ${what} (${miss.detail}): ${why}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
46
74
|
/** Why the converter leaves every render of a source on Enzyme. */
|
|
47
75
|
export type FileGate = "react" | "rtl" | "rtlMissing" | "commonjs";
|
|
48
76
|
|
|
@@ -51,8 +79,8 @@ const FILES: Readonly<Record<FileGate, string>> = {
|
|
|
51
79
|
"On React 19, migrate the file by hand to RTL 16's `render`, `screen` and `fireEvent`, following the file's other rows.",
|
|
52
80
|
rtl: "Blocked for this file by its React Testing Library: the recipe converts with RTL 12 on React 15.5 to 17, or RTL 16 on React 18. " +
|
|
53
81
|
"Move `@testing-library/react` to that version, then run the recipe again.",
|
|
54
|
-
rtlMissing: "Blocked for this file: the run added no React Testing Library
|
|
55
|
-
"
|
|
82
|
+
rtlMissing: "Blocked for this file: the run added no React Testing Library, as no package of the file declares Enzyme. " +
|
|
83
|
+
"Add `@testing-library/react` to the package that provides Enzyme to its tests, then run the recipe again.",
|
|
56
84
|
commonjs: "Blocked for this file by `require`: the recipe converts ES modules only. Load the file's modules with `import`, then run the recipe again."
|
|
57
85
|
};
|
|
58
86
|
|
|
@@ -60,14 +88,91 @@ export function blockedByFile(gate: FileGate): string {
|
|
|
60
88
|
return FILES[gate];
|
|
61
89
|
}
|
|
62
90
|
|
|
63
|
-
/**
|
|
64
|
-
export
|
|
65
|
-
|
|
91
|
+
/** Why a dependency step added no RTL to a package root that declares Enzyme, known once the step has generated. */
|
|
92
|
+
export type NotAdded = {kind: "withheld" | "peer" | "gate"} | {kind: "declined", warning?: string};
|
|
93
|
+
|
|
94
|
+
/** How the package manager declined an edit, read from the warning `AddDependency` leaves on the manifest. */
|
|
95
|
+
type Decline = "eresolve" | "engine" | "yarn" | "registry" | "other";
|
|
96
|
+
|
|
97
|
+
const DECLINES: Readonly<Record<Decline, string>> = {
|
|
98
|
+
eresolve: "npm rejects the edit with a peer dependency conflict (ERESOLVE). Where a plain `npm ci` of the unchanged repository fails too, " +
|
|
99
|
+
"the conflict is the repository's: resolve it, then run the recipe again.",
|
|
100
|
+
engine: "the recipe can't regenerate a lockfile of this package manager's version. Add `@testing-library/react` with the repository's own package manager, " +
|
|
101
|
+
"then run the recipe again.",
|
|
102
|
+
yarn: "yarn rejects the edit. Add `@testing-library/react` with the repository's yarn to see why, then run the recipe again.",
|
|
103
|
+
registry: "a registry request failed while the lockfile was regenerated. Run the recipe again.",
|
|
104
|
+
other: "the package manager declined the edit. Add `@testing-library/react` with the repository's own package manager to see why, then run the recipe again."
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
function declineOf(warning: string): Decline {
|
|
108
|
+
if (/ERESOLVE/.test(warning)) return "eresolve";
|
|
109
|
+
if (/pnpm \S+ is not a release|cannot know what \S+ \S+ writes/.test(warning)) return "engine";
|
|
110
|
+
if (/Failed to fetch|SocketTimeout|ETIMEDOUT|ECONNRESET|ENOTFOUND|EAI_AGAIN/.test(warning)) return "registry";
|
|
111
|
+
if (/yarn rejects/.test(warning)) return "yarn";
|
|
112
|
+
return "other";
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** What names the cause in a decline's warning, such as the packages of an npm peer conflict, short enough to group rows by. */
|
|
116
|
+
function declineDetail(decline: Decline, warning: string): string | undefined {
|
|
117
|
+
if (decline === "eresolve") {
|
|
118
|
+
// REGEX: the package npm was resolving, and the version it found that conflicts, from npm's ERESOLVE report
|
|
119
|
+
const resolving = /While resolving: (\S+)/.exec(warning)?.[1];
|
|
120
|
+
const found = /Found: (\S+)/.exec(warning)?.[1];
|
|
121
|
+
return resolving && found ? `\`${resolving}\` against \`${found}\`` : undefined;
|
|
122
|
+
}
|
|
123
|
+
// REGEX: a package manager and its version, such as "pnpm 10.11.0"
|
|
124
|
+
if (decline === "engine") return /\b(pnpm|yarn|npm|bun) (\d+\.\d+\.\d+)/.exec(warning)?.slice(1).join(" ");
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** The suggested action for a source kept on Enzyme because the run added no RTL to `root`, the package declaring Enzyme. */
|
|
129
|
+
export function blockedByPackage(root: string, outcome: NotAdded | undefined): string {
|
|
130
|
+
const manifest = `\`${root}package.json\``;
|
|
131
|
+
switch (outcome?.kind) {
|
|
132
|
+
case "withheld":
|
|
133
|
+
return `Blocked for this file: the run added no React Testing Library to ${manifest}, as no test in its lockfile converts with it. ` +
|
|
134
|
+
"Resolve the other review rows of these tests, then run the recipe again.";
|
|
135
|
+
case "peer":
|
|
136
|
+
return `Blocked for this file: the run added no React Testing Library 16 to ${manifest}, as its peer \`@testing-library/dom\` ` +
|
|
137
|
+
"was declined in the same lockfile. Add both with the repository's own package manager, then run the recipe again.";
|
|
138
|
+
case "gate":
|
|
139
|
+
return `Blocked for this file: the run added no React Testing Library to ${manifest}, as its lockfile doesn't resolve React and React DOM ` +
|
|
140
|
+
"to the versions that RTL supports. Install, so that the lockfile records them, then run the recipe again.";
|
|
141
|
+
case "declined": {
|
|
142
|
+
const decline = declineOf(outcome.warning ?? "");
|
|
143
|
+
const detail = declineDetail(decline, outcome.warning ?? "");
|
|
144
|
+
return `Blocked for this file: the run added no React Testing Library to ${manifest}${detail ? ` (${detail})` : ""}, as ${DECLINES[decline]}`;
|
|
145
|
+
}
|
|
146
|
+
default:
|
|
147
|
+
return FILES.rtlMissing;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The suggested action for a render that the uses at `references` keep on Enzyme, naming the first of them that isn't a snapshot the snapshot recipe converts. */
|
|
152
|
+
export async function blockedByUses(references: BlockingReference[]): Promise<string> {
|
|
153
|
+
const snapshots = references.filter(reference => reference.snapshot).length;
|
|
154
|
+
const first = references.find(reference => !reference.snapshot);
|
|
155
|
+
const uses = references.length > 1 ? `First of ${references.length} uses that keep it on Enzyme` : "The use";
|
|
156
|
+
if (!first) return `${SNAPSHOT} ${uses}: \`${await snippet(references[0].snapshot!)}\``;
|
|
66
157
|
const {top, calls} = chainOf(first.cursor);
|
|
67
158
|
const action = first.unmounted ? UNMOUNTED : actionFor(top, calls, first.cursor);
|
|
68
|
-
const
|
|
69
|
-
const
|
|
70
|
-
|
|
159
|
+
const shown = calls.length === 0 && !first.unmounted ? passedTo(first.cursor) ?? top : top;
|
|
160
|
+
const rest = snapshots === 0 ? "" : ` ${snapshots === 1 ? "Its snapshot assertion converts" : `Its ${snapshots} snapshot assertions convert`} ` +
|
|
161
|
+
`with ${SNAPSHOT_RECIPE} once the other uses do.`;
|
|
162
|
+
return `${action} ${uses}: \`${await snippet(shown)}\`${rest}`;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function snippet(node: J): Promise<string> {
|
|
166
|
+
// REGEX: the comments a statement starts with, which print with the node that begins it
|
|
167
|
+
const printed = (await TreePrinters.printer(JS.Kind.CompilationUnit).print(node)).replace(/^(\s*(\/\/[^\n]*|\/\*[\s\S]*?\*\/))+/, "")
|
|
168
|
+
.trim().replace(/\s+/g, " ");
|
|
169
|
+
return printed.length > 80 ? `${printed.slice(0, 77)}...` : printed;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** The call or `return` a bare wrapper is handed to, which says more than the wrapper's name. */
|
|
173
|
+
function passedTo(reference: Cursor): J | undefined {
|
|
174
|
+
const parent = reference.parentTree()?.value as J | undefined;
|
|
175
|
+
return parent?.kind === J.Kind.MethodInvocation || parent?.kind === J.Kind.NewClass || parent?.kind === J.Kind.Return ? parent : undefined;
|
|
71
176
|
}
|
|
72
177
|
|
|
73
178
|
export function blockedByGate(gate: RenderGate): string {
|
|
@@ -111,3 +216,63 @@ function actionFor(top: J, calls: J.MethodInvocation[], reference: Cursor): stri
|
|
|
111
216
|
if (event === "event") return SIMULATE_HERE;
|
|
112
217
|
return `Blocked by \`${api}\`: ${migrationReason(api, selector, event).suggestedAction}`;
|
|
113
218
|
}
|
|
219
|
+
|
|
220
|
+
/** A render of a shared wrapper whose own test converts, where another test of the wrapper keeps it on Enzyme. */
|
|
221
|
+
export function blockedByShared(name: string): string {
|
|
222
|
+
return `Blocked by another test of the shared \`${name}\`: the recipe converts a wrapper that its tests or a \`beforeEach\` assign only where every test of it converts. ` +
|
|
223
|
+
"This test's uses convert, so see the rows of the other tests.";
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const HELD = "the recipe converts a render that a `const` of the test declares, or one held in a `let` declared without a value that each test, " +
|
|
227
|
+
"or the last statement of a `beforeEach`, assigns before any other use.";
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Why a render the converter didn't analyze stays on Enzyme, where its shape says so: a render held in a `let`, `var` or
|
|
231
|
+
* assignment, or returned from a named function. Any other shape gets nothing, which keeps the generic action.
|
|
232
|
+
*/
|
|
233
|
+
export function blockedByShape(render: Cursor): string | undefined {
|
|
234
|
+
const call = render.value as J.MethodInvocation;
|
|
235
|
+
const api = call.name.simpleName;
|
|
236
|
+
const parent = render.parentTree();
|
|
237
|
+
const node = parent?.value as J | undefined;
|
|
238
|
+
if (node?.kind === J.Kind.NamedVariable && (node as J.VariableDeclarations.NamedVariable).initializer?.element === call) {
|
|
239
|
+
const variable = node as J.VariableDeclarations.NamedVariable;
|
|
240
|
+
const declaration = parent!.parentTree()?.value as J | undefined;
|
|
241
|
+
const keyword = declaration?.kind === J.Kind.VariableDeclarations ?
|
|
242
|
+
(declaration as J.VariableDeclarations).modifiers.find(modifier => modifier.keyword === "let" || modifier.keyword === "var")?.keyword : undefined;
|
|
243
|
+
if (!keyword || !isIdentifier(variable.name)) return undefined;
|
|
244
|
+
const name = variable.name.simpleName;
|
|
245
|
+
return `Blocked by \`${keyword} ${name}\`: ${HELD} Give each render a \`const\` of its own, such as \`const ${name} = ${api}(...)\`, in the test that reads it.`;
|
|
246
|
+
}
|
|
247
|
+
if (node?.kind === J.Kind.Assignment && (node as J.Assignment).assignment.element === call) {
|
|
248
|
+
const target = (node as J.Assignment).variable;
|
|
249
|
+
if (!isIdentifier(target)) return undefined;
|
|
250
|
+
const name = target.simpleName;
|
|
251
|
+
return `Blocked by assigning the render to \`${name}\`: ${HELD} Otherwise give each render a \`const\` of its own, such as \`const ${name} = ${api}(...)\`, in the test that reads it.`;
|
|
252
|
+
}
|
|
253
|
+
const returning = node?.kind === J.Kind.Return && (node as J.Return).expression === call ? enclosingFunction(parent!) :
|
|
254
|
+
node?.kind === J.Kind.Lambda && (node as J.Lambda).body === call ? parent : undefined;
|
|
255
|
+
const name = returning && functionName(returning);
|
|
256
|
+
if (!name) return undefined;
|
|
257
|
+
return `Blocked by a render that \`${name}\` returns: the recipe converts a render where the test that reads it declares it. ` +
|
|
258
|
+
`Render in each test with \`const wrapper = ${api}(...)\`, or have \`${name}\` return the result of RTL's \`render\` and change what its callers read by hand.`;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function enclosingFunction(cursor: Cursor): Cursor | undefined {
|
|
262
|
+
for (let c = cursor.parentTree(); c; c = c.parentTree()) {
|
|
263
|
+
const kind = (c.value as J).kind;
|
|
264
|
+
if (kind === J.Kind.MethodDeclaration || kind === J.Kind.Lambda) return c;
|
|
265
|
+
}
|
|
266
|
+
return undefined;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** The name of a function declaration, or of the variable an arrow function initializes; a callback has none. */
|
|
270
|
+
function functionName(fn: Cursor): string | undefined {
|
|
271
|
+
const node = fn.value as J;
|
|
272
|
+
if (node.kind === J.Kind.MethodDeclaration) return (node as J.MethodDeclaration).name.simpleName;
|
|
273
|
+
let outer = fn.parentTree();
|
|
274
|
+
if ((outer?.value as J | undefined)?.kind === JS.Kind.ArrowFunction) outer = outer!.parentTree();
|
|
275
|
+
const holder = outer?.value as J | undefined;
|
|
276
|
+
return holder?.kind === J.Kind.NamedVariable && isIdentifier((holder as J.VariableDeclarations.NamedVariable).name) ?
|
|
277
|
+
((holder as J.VariableDeclarations.NamedVariable).name as J.Identifier).simpleName : undefined;
|
|
278
|
+
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, or, randomId, RecipeRef, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
|
|
1
|
+
import {and, check, Cursor, DataTable, ExecutionContext, findMarker, MarkersKind, MarkupWarn, not, Option, or, randomId, RecipeRef, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
|
|
2
2
|
import {isPlainText} from "@openrewrite/rewrite/text";
|
|
3
|
-
import {AddDependencyOptions, autoFormat, Autodetect, capture, PrettierStyle, deconflict, findNodeResolutionResult, isTypeScript, isVendoredOrBundled, JavaScriptVisitor, JS, maybeAddImport, maybeRemoveImport, moduleBindings, namesUsedIn, pattern, raw, rewrite, scopeOf, StyleKind, Template, template, usesMethod} from "@openrewrite/rewrite/javascript";
|
|
4
|
-
import {Expression, J} from "@openrewrite/rewrite/java";
|
|
3
|
+
import {AddDependencyOptions, autoFormat, Autodetect, capture, PrettierStyle, deconflict, findNodeResolutionResult, isTypeScript, isVendoredOrBundled, JavaScriptVisitor, JS, maybeAddImport, maybeRemoveImport, moduleBindings, namesUsedIn, pattern, walk, raw, rewrite, scopeOf, StyleKind, Template, template, usesMethod} from "@openrewrite/rewrite/javascript";
|
|
4
|
+
import {Expression, isIdentifier, J, Type, TypedTree} from "@openrewrite/rewrite/java";
|
|
5
5
|
import {create} from "mutative";
|
|
6
6
|
import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
|
|
7
7
|
import {readFileSync} from "fs";
|
|
@@ -10,9 +10,9 @@ import {satisfies, valid, validRange} from "semver";
|
|
|
10
10
|
import {FindEnzymeUsage} from "../search/find-enzyme-usage";
|
|
11
11
|
import {JavaDependencyRecipe, treesOfType} from "../util/java-recipe-proxy";
|
|
12
12
|
import {importBindings} from "../util/module-imports";
|
|
13
|
-
import {ENZYME, ENZYME_USAGE_TABLE, enclosingScope, enzymeMethod, EnzymeUsageRow, FILE_BLOCKER, RENDER_BLOCKERS} from "./enzyme-usage";
|
|
14
|
-
import {blockedByFile, blockedByGate, blockedByUses, FileGate} from "./enzyme-render-blockers";
|
|
15
|
-
import {HostComponents, hostComponentExports, hostComponentsDeclared, ImportedExport, importedNames, propsRenderHostElements, relativeImports, rendersHostElements} from "./enzyme-host-components";
|
|
13
|
+
import {ENZYME, ENZYME_USAGE_TABLE, enclosingScope, enzymeMethod, EnzymeUsageRow, FILE_BLOCKER, RENDER_BLOCKERS, SELECTOR_VALUES, SelectorRead} from "./enzyme-usage";
|
|
14
|
+
import {blockedByFile, blockedByGate, blockedByShape, blockedByShared, blockedByPackage, blockedByShallow, blockedByUses, FileGate, NotAdded} from "./enzyme-render-blockers";
|
|
15
|
+
import {compositeFacts, Composites, HostComponents, hostComponentExports, shallowMiss, hostComponentsDeclared, ImportedExport, importedNames, propsRenderHostElements, relativeImports, rendersHostElements} from "./enzyme-host-components";
|
|
16
16
|
import {moduleFacts, Modules, rendersPortal, resolver} from "./enzyme-portals";
|
|
17
17
|
import {evaluate, stringParts} from "./enzyme-constant-strings";
|
|
18
18
|
import {hostOnlyNames, selectorNames, SelectorNames} from "./enzyme-selector-names";
|
|
@@ -82,6 +82,9 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
|
|
|
82
82
|
/** The package roots whose edit `AddDependency` declined, such as for a lockfile it could not regenerate. Mutated in place too. */
|
|
83
83
|
readonly declined = new Set<string>();
|
|
84
84
|
|
|
85
|
+
/** Why the dependency didn't land in each package root declaring Enzyme that it didn't land in. Mutated in place too. */
|
|
86
|
+
readonly outcomes = new Map<string, NotAdded>();
|
|
87
|
+
|
|
85
88
|
private readonly manifests: Json.Document[] = [];
|
|
86
89
|
|
|
87
90
|
/** The manifests the step admits, which reach the Java recipe only in `generate`, once the forecast is known. */
|
|
@@ -94,6 +97,7 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
|
|
|
94
97
|
override initialValue(): number {
|
|
95
98
|
this.landed.clear();
|
|
96
99
|
this.declined.clear();
|
|
100
|
+
this.outcomes.clear();
|
|
97
101
|
this.manifests.length = 0;
|
|
98
102
|
this.held.length = 0;
|
|
99
103
|
return super.initialValue();
|
|
@@ -126,10 +130,16 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
|
|
|
126
130
|
// Without a forecast, as when the step runs alone, every admitted manifest goes on as before
|
|
127
131
|
const converting = await this.forecast.converting?.();
|
|
128
132
|
const scopes = lockfileScopes(this.held);
|
|
129
|
-
const
|
|
133
|
+
const withheld = (manifest: Json.Document): NotAdded | undefined => {
|
|
130
134
|
const scope = scopes.get(manifest.sourcePath) ?? packageRoot(manifest.sourcePath);
|
|
131
|
-
|
|
132
|
-
|
|
135
|
+
if (converting && ![...converting].some(source => source.startsWith(scope))) return {kind: "withheld"};
|
|
136
|
+
return this.withholds(scope) ? {kind: "peer"} : undefined;
|
|
137
|
+
};
|
|
138
|
+
const forwarded = new Set(this.held.filter(manifest => !withheld(manifest)));
|
|
139
|
+
for (const manifest of this.manifests) {
|
|
140
|
+
const why = forwarded.has(manifest) ? undefined : withheld(manifest);
|
|
141
|
+
if (why) this.outcomes.set(packageRoot(manifest.sourcePath), why);
|
|
142
|
+
}
|
|
133
143
|
const scanner = await this.java.scanner(acc);
|
|
134
144
|
for (const manifest of forwarded) await scanner.visit(manifest, ctx);
|
|
135
145
|
const kept = this.manifests.filter(manifest => forwarded.has(manifest));
|
|
@@ -141,7 +151,12 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
|
|
|
141
151
|
const edited = await editor.visit<Json.Document>(manifest, ctx);
|
|
142
152
|
const root = manifest.sourcePath.slice(0, -"package.json".length);
|
|
143
153
|
if (edited && edited !== manifest && declares(edited, this.addition.packageName)) this.landed.add(root);
|
|
144
|
-
else if (!declares(manifest, this.addition.packageName) && this.resolvesGate(manifest))
|
|
154
|
+
else if (!declares(manifest, this.addition.packageName) && this.resolvesGate(manifest)) {
|
|
155
|
+
this.declined.add(root);
|
|
156
|
+
// NOTE: `AddDependency` leaves why it declined as a warning on the manifest it returns
|
|
157
|
+
const warning = (edited ?? manifest).markers.markers.find(marker => marker.kind === MarkersKind.MarkupWarn) as MarkupWarn | undefined;
|
|
158
|
+
this.outcomes.set(root, {kind: "declined", warning: warning && [warning.message, warning.detail].filter(Boolean).join("\n")});
|
|
159
|
+
} else if (!declares(manifest, this.addition.packageName)) this.outcomes.set(root, {kind: "gate"});
|
|
145
160
|
}
|
|
146
161
|
return generated;
|
|
147
162
|
}
|
|
@@ -363,6 +378,8 @@ type Packages = Map<string, PackageDeclarations>;
|
|
|
363
378
|
interface Scanned {
|
|
364
379
|
packages: Packages;
|
|
365
380
|
components: HostComponents;
|
|
381
|
+
/** What the components of each source render that `shallow` leaves out, for a review row's action. */
|
|
382
|
+
composites: Composites;
|
|
366
383
|
modules: Modules;
|
|
367
384
|
/** The words of each source's strings, for the selectors whose ancestor compounds name no tag. */
|
|
368
385
|
names: Map<string, SelectorNames>;
|
|
@@ -442,8 +459,17 @@ export function simulatesEvents(packages: Packages, sourcePath: string, landed:
|
|
|
442
459
|
return {events: new Set(), attached: false};
|
|
443
460
|
}
|
|
444
461
|
|
|
462
|
+
/**
|
|
463
|
+
* The package root a source's RTL goes to, that of the package declaring Enzyme, and whether its React is 18, which
|
|
464
|
+
* decides the dependency step that adds it. Undefined where no package of the source declares or provides Enzyme.
|
|
465
|
+
*/
|
|
466
|
+
export function rtlTarget(packages: Packages, sourcePath: string): {root: string, react18: boolean} | undefined {
|
|
467
|
+
const {enzymeRoot, enzymeReact} = compatibility(packages, sourcePath, new Set());
|
|
468
|
+
return enzymeRoot === undefined ? undefined : {root: enzymeRoot, react18: enzymeReact === 18};
|
|
469
|
+
}
|
|
470
|
+
|
|
445
471
|
/** The React major as {@link reactMajor} reads it, and the major of the RTL the tests run with. */
|
|
446
|
-
function compatibility(packages: Packages, sourcePath: string, landed: ReadonlySet<string>): {react: number, rtl: number, why?: FileGate} {
|
|
472
|
+
function compatibility(packages: Packages, sourcePath: string, landed: ReadonlySet<string>): {react: number, rtl: number, why?: FileGate, enzymeRoot?: string, enzymeReact?: number} {
|
|
447
473
|
const roots = [...packages.keys()].filter(root => sourcePath.startsWith(root)).sort((a, b) => b.length - a.length);
|
|
448
474
|
const declared = (name: "react" | "reactDom" | "rtl", from = roots) =>
|
|
449
475
|
from.map(root => packages.get(root)![name]).find(version => version !== undefined);
|
|
@@ -464,10 +490,11 @@ function compatibility(packages: Packages, sourcePath: string, landed: ReadonlyS
|
|
|
464
490
|
const rtlMajor = added ? ((enzymeReact as DeclaredVersion).major >= 18 ? 16 : 12) : typeof rtl === "object" && rtl.major >= 10 && rtl.major <= 16 ? rtl.major : 0;
|
|
465
491
|
const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major &&
|
|
466
492
|
rtlMajor > 0 && rtlSupports(rtlMajor, react.major);
|
|
467
|
-
|
|
493
|
+
const target = {enzymeRoot: enzymeRoots[0], enzymeReact: supportedReact(enzymeReact) ? enzymeReact.major : undefined};
|
|
494
|
+
if (compatible) return {react: react.major, rtl: rtlMajor, ...target};
|
|
468
495
|
const why: FileGate = !supportedReact(react) || !supportedReact(reactDom) || react.major !== reactDom.major ? "react" :
|
|
469
496
|
rtl === undefined && !added ? "rtlMissing" : "rtl";
|
|
470
|
-
return {react: 0, rtl: rtlMajor, why};
|
|
497
|
+
return {react: 0, rtl: rtlMajor, why, ...target};
|
|
471
498
|
}
|
|
472
499
|
|
|
473
500
|
/**
|
|
@@ -573,7 +600,7 @@ function withoutStatements(block: J.Block, removed: ReadonlySet<string>): J.Bloc
|
|
|
573
600
|
export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
574
601
|
readonly name: string = "org.openrewrite.react.migrate.enzyme-to-react-testing-library";
|
|
575
602
|
readonly displayName: string = "Migrate Enzyme to React Testing Library";
|
|
576
|
-
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 15.5 and 16) and bare `mount` statements to React Testing Library container queries, `rerender`, and `fireEvent` in packages using React 16 or 17 with RTL 10 to 12, React 15.5+ with RTL 12, or React 18 with RTL 16, adding RTL 12, or RTL 16 with its peer `@testing-library/dom` 10, where it is missing. On React 15, whose markup differs, `html()` and DOM nodes are left for review. 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;
|
|
603
|
+
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 15.5 and 16) and bare `mount` statements to React Testing Library container queries, `rerender`, and `fireEvent` in packages using React 16 or 17 with RTL 10 to 12, React 15.5+ with RTL 12, or React 18 with RTL 16, adding RTL 12, or RTL 16 with its peer `@testing-library/dom` 10, where it is missing. This includes a shared `let` wrapper that each test assigns first, or that the last statement of a `beforeEach` assigns, where every test of it converts. On React 15, whose markup differs, `html()` and DOM nodes are left for review. 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; props, snapshots, and shallow rendering of other components are left for review.";
|
|
577
604
|
|
|
578
605
|
@Option({
|
|
579
606
|
displayName: "Convert positions into untagged selector matches",
|
|
@@ -588,6 +615,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
588
615
|
// PERF: the sources that import Enzyme, kept from the scan to the forecast in `generate`, as the dependency steps keep
|
|
589
616
|
// their manifests. Not in the accumulator, which the host keeps until the cycle ends; cleared once the forecast is made.
|
|
590
617
|
private readonly tests: JS.CompilationUnit[] = [];
|
|
618
|
+
// What kept each render on Enzyme in the forecast, where RTL is taken to land, for the sources of a package it withholds RTL from
|
|
619
|
+
private readonly forecastBlockers = new Map<string, ReadonlyMap<string, string>>();
|
|
591
620
|
private readonly dependencySteps = ADDS_RTL ? dependencySteps(this.forecast) : undefined;
|
|
592
621
|
|
|
593
622
|
constructor(options?: {untaggedSelectorPositions?: boolean}) {
|
|
@@ -605,7 +634,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
605
634
|
|
|
606
635
|
initialValue(): Scanned {
|
|
607
636
|
this.tests.length = 0;
|
|
608
|
-
|
|
637
|
+
this.forecastBlockers.clear();
|
|
638
|
+
return {packages: new Map(), components: new Map(), composites: new Map(), modules: new Map(), names: new Map(), nullSnapshots: new Set()};
|
|
609
639
|
}
|
|
610
640
|
|
|
611
641
|
// The host may prepare the visitors before there is an accumulator, so it is read only while visiting
|
|
@@ -618,6 +648,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
618
648
|
const sources = new class extends JavaScriptVisitor<ExecutionContext> {
|
|
619
649
|
override async visitJsCompilationUnit(cu: JS.CompilationUnit): Promise<J | undefined> {
|
|
620
650
|
scanned.components.set(cu.sourcePath, hostComponentExports(cu));
|
|
651
|
+
const composite = compositeFacts(cu);
|
|
652
|
+
if (composite) scanned.composites.set(cu.sourcePath, composite);
|
|
621
653
|
scanned.modules.set(cu.sourcePath, moduleFacts(cu));
|
|
622
654
|
scanned.names.set(cu.sourcePath, selectorNames(cu));
|
|
623
655
|
if (importBindings(cu).some(({module}) => module === ENZYME)) tests.push(cu);
|
|
@@ -740,6 +772,18 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
740
772
|
};
|
|
741
773
|
const usages = this.usages;
|
|
742
774
|
const steps = this.dependencySteps;
|
|
775
|
+
const forecastBlockers = this.forecastBlockers;
|
|
776
|
+
// Why the run added no RTL for a source, from the step that adds the RTL its package's React takes. Where the
|
|
777
|
+
// forecast withheld it, what kept each render on Enzyme in the forecast is what to resolve first.
|
|
778
|
+
const notAdded = (sourcePath: string): ReadonlyMap<string, string> => {
|
|
779
|
+
const target = rtlTarget(scanned.packages, sourcePath);
|
|
780
|
+
if (!target) return new Map([[FILE_BLOCKER, blockedByFile("rtlMissing")]]);
|
|
781
|
+
const outcome = !steps ? undefined : target.react18 ?
|
|
782
|
+
steps.dom18.outcomes.get(target.root) ?? steps.rtl18.outcomes.get(target.root) : steps.rtl.outcomes.get(target.root);
|
|
783
|
+
const blockers = new Map([[FILE_BLOCKER, blockedByPackage(target.root, outcome)]]);
|
|
784
|
+
if (outcome?.kind === "withheld") forecastBlockers.get(sourcePath)?.forEach((why, id) => blockers.set(id, why));
|
|
785
|
+
return blockers;
|
|
786
|
+
};
|
|
743
787
|
const untaggedPositions = this.untaggedSelectorPositions !== false;
|
|
744
788
|
const snapshots = this.snapshots;
|
|
745
789
|
return check(and(not(isVendoredOrBundled()), or(usesMethod("enzyme mount(..)"), usesMethod("enzyme shallow(..)"))), new class extends JavaScriptVisitor<ExecutionContext> {
|
|
@@ -754,12 +798,15 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
754
798
|
private readonly mounts = new Map<string, ConvertedRender>();
|
|
755
799
|
private imports: ReadonlyMap<string, ImportedExport> = new Map();
|
|
756
800
|
private importedNames: ReadonlySet<string> = new Set();
|
|
801
|
+
private bindings: ReturnType<typeof importBindings> = [];
|
|
757
802
|
private declaredHost: ReadonlySet<string> = new Set();
|
|
758
803
|
private readonly uses = new Map<string, WrapperRead>();
|
|
759
804
|
private readonly removedStatements = new Set<string>();
|
|
760
805
|
private readonly unmounts = new Set<string>();
|
|
761
806
|
private readonly declarations = new Set<string>();
|
|
762
807
|
private readonly pending = new Set<string>();
|
|
808
|
+
// The renders of shared wrappers, whose shape the recipe converts, so blockShapes leaves them alone
|
|
809
|
+
private readonly sharedRenders = new Set<string>();
|
|
763
810
|
private readonly reformat = new Set<string>();
|
|
764
811
|
private readonly hoists = new Map<string, HoistedElement>();
|
|
765
812
|
private readonly hoistedMounts = new Map<string, string>();
|
|
@@ -774,12 +821,13 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
774
821
|
|
|
775
822
|
override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
|
|
776
823
|
this.sourcePath = cu.sourcePath;
|
|
777
|
-
[this.mounts, this.uses, this.removedStatements, this.unmounts, this.declarations, this.pending, this.reformat].forEach(ids => ids.clear());
|
|
824
|
+
[this.mounts, this.uses, this.removedStatements, this.unmounts, this.declarations, this.pending, this.reformat, this.sharedRenders].forEach(ids => ids.clear());
|
|
778
825
|
this.hoists.clear();
|
|
779
826
|
this.hoistedMounts.clear();
|
|
780
827
|
this.rows.length = 0;
|
|
781
828
|
this.blockers.clear();
|
|
782
829
|
if (!dry) RENDER_BLOCKERS.delete(cu.sourcePath);
|
|
830
|
+
if (!dry) await this.readSelectors(cu);
|
|
783
831
|
this.names = namesUsedIn(cu);
|
|
784
832
|
const prettierStyle = findMarker<PrettierStyle>(cu, StyleKind.PrettierStyle);
|
|
785
833
|
this.prettier = prettierStyle !== undefined && !prettierStyle.ignored && await formattedBy(cu, prettierStyle);
|
|
@@ -795,10 +843,12 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
795
843
|
if (!this.enabled) {
|
|
796
844
|
// Every render of the file stays on Enzyme for the same reason
|
|
797
845
|
const why = this.reactMajor === 0 ? incompatibility(scanned.packages, cu.sourcePath, landed) : "commonjs";
|
|
798
|
-
if (
|
|
846
|
+
if (dry && why && why !== "rtlMissing") forecastBlockers.set(cu.sourcePath, new Map([[FILE_BLOCKER, blockedByFile(why)]]));
|
|
847
|
+
if (!dry && why) RENDER_BLOCKERS.set(cu.sourcePath, why === "rtlMissing" ? notAdded(cu.sourcePath) : new Map([[FILE_BLOCKER, blockedByFile(why)]]));
|
|
799
848
|
return cu;
|
|
800
849
|
}
|
|
801
850
|
this.imports = relativeImports(cu, scanned.components);
|
|
851
|
+
this.bindings = importBindings(cu);
|
|
802
852
|
this.importedNames = importedNames(cu);
|
|
803
853
|
this.declaredHost = hostComponentsDeclared(cu);
|
|
804
854
|
// Templates lay out what they insert with the source's Prettier style, which a source its config does not lay out keeps out of
|
|
@@ -813,8 +863,10 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
813
863
|
const visited = await super.visitJsCompilationUnit(visiting, ctx);
|
|
814
864
|
if (dry) {
|
|
815
865
|
if (this.rows.some(row => row.status === "CONVERTED")) dry.converted.add(cu.sourcePath);
|
|
866
|
+
if (this.blockers.size > 0) forecastBlockers.set(cu.sourcePath, new Map(this.blockers));
|
|
816
867
|
} else {
|
|
817
868
|
this.rows.forEach(row => usages.insertRow(ctx, row));
|
|
869
|
+
await this.blockShapes(cu, ctx);
|
|
818
870
|
if (this.blockers.size > 0) RENDER_BLOCKERS.set(cu.sourcePath, new Map(this.blockers));
|
|
819
871
|
}
|
|
820
872
|
if (!foreign || !visited) return visited;
|
|
@@ -834,9 +886,23 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
834
886
|
const converted = await this.convertBlock(candidate, ctx);
|
|
835
887
|
this.cursor = original;
|
|
836
888
|
// Each test's wrapper converts, or the shared wrapper and every test keep Enzyme
|
|
837
|
-
if (mounts.every(id => this.mounts.has(id) && !this.pending.has(id))) return this.renderedInHooks(converted as J.Block, block, shared, ctx);
|
|
889
|
+
if (mounts.every(({id}) => this.mounts.has(id) && !this.pending.has(id))) return this.renderedInHooks(converted as J.Block, block, shared, ctx);
|
|
890
|
+
// What kept each test's copy of the render on Enzyme is what keeps the shared render there
|
|
891
|
+
const kept = new Map<string, string>();
|
|
892
|
+
for (const {id, from} of mounts) {
|
|
893
|
+
const why = this.blockers.get(id);
|
|
894
|
+
if (why && !kept.has(from)) kept.set(from, why);
|
|
895
|
+
}
|
|
896
|
+
for (const {id, from, name} of mounts) {
|
|
897
|
+
if (!kept.has(from) && this.mounts.has(id) && !this.pending.has(id)) kept.set(from, blockedByShared(name));
|
|
898
|
+
}
|
|
838
899
|
this.restoreState(saved);
|
|
839
|
-
|
|
900
|
+
const plain = await this.convertBlock(block, ctx);
|
|
901
|
+
mounts.forEach(({from}) => this.sharedRenders.add(from));
|
|
902
|
+
kept.forEach((why, id) => {
|
|
903
|
+
if (!this.blockers.has(id)) this.blockers.set(id, why);
|
|
904
|
+
});
|
|
905
|
+
return plain;
|
|
840
906
|
}
|
|
841
907
|
|
|
842
908
|
/**
|
|
@@ -947,7 +1013,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
947
1013
|
* cleanup in `afterEach`, or the tests clearing it. An unmount that `afterEach` does before other statements
|
|
948
1014
|
* becomes RTL's `cleanup()`, which keeps the order, and one after them is dropped, as RTL unmounts after them too.
|
|
949
1015
|
*/
|
|
950
|
-
private async mountedInEachTest(block: J.Block, shared: SharedWrapper[], ctx: ExecutionContext): Promise<{candidate: J.Block, mounts: string[]}> {
|
|
1016
|
+
private async mountedInEachTest(block: J.Block, shared: SharedWrapper[], ctx: ExecutionContext): Promise<{candidate: J.Block, mounts: {id: string, from: string, name: string}[]}> {
|
|
951
1017
|
const names = new Map<string, string>();
|
|
952
1018
|
shared.forEach(wrapper => wrapper.assignments.forEach(id => names.set(id, wrapper.name)));
|
|
953
1019
|
const cleanup = new Set(shared.flatMap(wrapper => [...wrapper.cleanup]));
|
|
@@ -961,7 +1027,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
961
1027
|
};
|
|
962
1028
|
const removed = new Set(shared.flatMap(wrapper => [wrapper.declaration.id, ...wrapper.afterEach && whole(wrapper.afterEach) ? [wrapper.afterEach.id] : []]));
|
|
963
1029
|
const trimmed = withoutStatements(block, removed);
|
|
964
|
-
const mounts: string[] = [];
|
|
1030
|
+
const mounts: {id: string, from: string, name: string}[] = [];
|
|
965
1031
|
const outer = this;
|
|
966
1032
|
const candidate = await new class extends JavaScriptVisitor<ExecutionContext> {
|
|
967
1033
|
override async visitBlock(inner: J.Block, p: ExecutionContext): Promise<J | undefined> {
|
|
@@ -1003,7 +1069,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
1003
1069
|
const declare = Template.builder().code(`const ${name} = `).param(assignment.assignment.element).build();
|
|
1004
1070
|
const declared = await declare.apply(statement.element, cursor) as J.VariableDeclarations | undefined;
|
|
1005
1071
|
if (!declared) throw new Error(`Cannot declare ${name}`);
|
|
1006
|
-
mounts.push(declared.variables[0].element.initializer!.element.id);
|
|
1072
|
+
mounts.push({id: declared.variables[0].element.initializer!.element.id, from: assignment.assignment.element.id, name});
|
|
1007
1073
|
statements.push({...statement, element: {...declared, prefix: statement.element.prefix}});
|
|
1008
1074
|
}
|
|
1009
1075
|
return withoutStatements(create(visited, draft => {
|
|
@@ -1021,7 +1087,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
1021
1087
|
const declare = Template.builder().code(`const ${hooked.name} = `).param(withNewIds(hooked.mount)).build();
|
|
1022
1088
|
const declared = await declare.apply(first.element, cursor) as J.VariableDeclarations | undefined;
|
|
1023
1089
|
if (!declared) throw new Error(`Cannot declare ${hooked.name}`);
|
|
1024
|
-
mounts.push(declared.variables[0].element.initializer!.element.id);
|
|
1090
|
+
mounts.push({id: declared.variables[0].element.initializer!.element.id, from: hooked.mount.id, name: hooked.name});
|
|
1025
1091
|
const semicolon = test.statements.some(padded => padded.markers.markers.some(marker => marker.kind === J.Markers.Semicolon));
|
|
1026
1092
|
const padded = {...first, element: {...declared, prefix: first.element.prefix},
|
|
1027
1093
|
markers: {...first.markers, markers: semicolon ? [{kind: J.Markers.Semicolon, id: randomId()}] : []}};
|
|
@@ -1072,7 +1138,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
1072
1138
|
// React 15 marks its markup with `data-reactroot` and empty renders with comments, which Enzyme's html() leaves out
|
|
1073
1139
|
const markup = this.reactMajor >= 16;
|
|
1074
1140
|
let blocking: Parameters<typeof blockedByUses>[0] | undefined;
|
|
1075
|
-
const scope = analyzeWrapperScope(this.cursor, candidate, {events: reads.simulate ? this.events.events : new Set(), html: reads.html && markup, untaggedPositions, hostNames, snapshots: snapshots && markup, optionalChaining: this.optionalChaining,
|
|
1141
|
+
const scope = analyzeWrapperScope(this.cursor, candidate, {events: reads.simulate ? this.events.events : new Set(), html: reads.html && markup, untaggedPositions, hostNames, snapshots: snapshots && markup, optInSnapshots: !snapshots && markup, optionalChaining: this.optionalChaining,
|
|
1076
1142
|
constant: node => this.constantString(node), blocked: references => blocking = references});
|
|
1077
1143
|
if (!scope) {
|
|
1078
1144
|
if (blocking) this.blockers.set(candidate.mount.id, await blockedByUses(blocking));
|
|
@@ -1345,7 +1411,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
1345
1411
|
if (api !== "shallow" || call.arguments.elements.length !== 1) return undefined;
|
|
1346
1412
|
const element = call.arguments.elements[0]?.element;
|
|
1347
1413
|
if (rendersHostElements(element, this.imports, scanned.components, this.importedNames, this.declaredHost)) return api;
|
|
1348
|
-
this.blockers.set(call.id,
|
|
1414
|
+
this.blockers.set(call.id, blockedByShallow(shallowMiss(element, this.imports, scanned.components, scanned.composites, this.bindings)));
|
|
1349
1415
|
return undefined;
|
|
1350
1416
|
}
|
|
1351
1417
|
|
|
@@ -1380,6 +1446,74 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
|
|
|
1380
1446
|
return {roots, declares, resolve: resolver(scanned.modules, [...new Set([...roots, ""])], declares)};
|
|
1381
1447
|
}
|
|
1382
1448
|
|
|
1449
|
+
/** Records what each `find` selector of `cu` written as other than a literal holds, for its review row. */
|
|
1450
|
+
/** Names the shape that kept each render the conversion didn't analyze, where the shape says why. */
|
|
1451
|
+
private async blockShapes(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<void> {
|
|
1452
|
+
const blockers = this.blockers;
|
|
1453
|
+
const mounts = this.mounts;
|
|
1454
|
+
const sharedRenders = this.sharedRenders;
|
|
1455
|
+
await new class extends JavaScriptVisitor<ExecutionContext> {
|
|
1456
|
+
override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
|
|
1457
|
+
const api = enzymeMethod(method);
|
|
1458
|
+
if ((api === "mount" || api === "shallow") && !blockers.has(method.id) && !mounts.has(method.id) && !sharedRenders.has(method.id)) {
|
|
1459
|
+
const why = blockedByShape(this.cursor);
|
|
1460
|
+
if (why) blockers.set(method.id, why);
|
|
1461
|
+
}
|
|
1462
|
+
return super.visitMethodInvocation(method, ctx);
|
|
1463
|
+
}
|
|
1464
|
+
}().visit(cu, ctx);
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
private async readSelectors(cu: JS.CompilationUnit): Promise<void> {
|
|
1468
|
+
SELECTOR_VALUES.delete(cu.sourcePath);
|
|
1469
|
+
const finds: J.MethodInvocation[] = [];
|
|
1470
|
+
walk(cu, tree => {
|
|
1471
|
+
if (tree.kind === J.Kind.MethodInvocation && enzymeMethod(tree as J.MethodInvocation) === "find" &&
|
|
1472
|
+
(tree as J.MethodInvocation).arguments.elements.length === 1) finds.push(tree as J.MethodInvocation);
|
|
1473
|
+
return true;
|
|
1474
|
+
});
|
|
1475
|
+
const topLevel = new Set(cu.statements.map(({element}) =>
|
|
1476
|
+
element.kind === JS.Kind.ExportDeclaration ? (element as JS.ExportDeclaration).exportClause?.id : element.id));
|
|
1477
|
+
// The resolver reads only top-level constants, so a name a nested `const` declares may hold a string after all
|
|
1478
|
+
const nested = new Set<string>();
|
|
1479
|
+
walk(cu, tree => {
|
|
1480
|
+
if (tree.kind !== J.Kind.VariableDeclarations || topLevel.has(tree.id)) return true;
|
|
1481
|
+
const variables = tree as J.VariableDeclarations;
|
|
1482
|
+
if (!variables.modifiers.some(modifier => modifier.keyword === "const")) return true;
|
|
1483
|
+
for (const {element: variable} of variables.variables) {
|
|
1484
|
+
if (isIdentifier(variable.name) && variable.initializer && stringParts(variable.initializer.element)) nested.add(variable.name.simpleName);
|
|
1485
|
+
}
|
|
1486
|
+
return true;
|
|
1487
|
+
});
|
|
1488
|
+
const reads = new Map<string, SelectorRead>();
|
|
1489
|
+
for (const find of finds) {
|
|
1490
|
+
const read = await this.selectorRead(find.arguments.elements[0].element, nested);
|
|
1491
|
+
if (read) reads.set(find.id, read);
|
|
1492
|
+
}
|
|
1493
|
+
if (reads.size > 0) SELECTOR_VALUES.set(cu.sourcePath, reads);
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1496
|
+
/** What a selector holds that is a template or a string-typed name, or the first part of it that isn't a constant string. */
|
|
1497
|
+
private async selectorRead(selector: J, nested: ReadonlySet<string>): Promise<SelectorRead | undefined> {
|
|
1498
|
+
const named = (name: string) => evaluate([{name}], this.sourcePath, scanned.modules, this.moduleResolution().resolve);
|
|
1499
|
+
const printed = async (node: J) => (await TreePrinters.printer(JS.Kind.CompilationUnit).print(node)).trim().replace(/\s+/g, " ");
|
|
1500
|
+
if (selector.kind === JS.Kind.TemplateExpression) {
|
|
1501
|
+
const value = this.constantString(selector);
|
|
1502
|
+
if (value !== undefined) return {value};
|
|
1503
|
+
for (const {element: span} of (selector as JS.TemplateExpression).spans) {
|
|
1504
|
+
const part = span.expression;
|
|
1505
|
+
if (isIdentifier(part) && nested.has(part.simpleName)) return undefined;
|
|
1506
|
+
if (!isIdentifier(part) || named(part.simpleName) === undefined) return {unread: await printed(part)};
|
|
1507
|
+
}
|
|
1508
|
+
return undefined;
|
|
1509
|
+
}
|
|
1510
|
+
const value = isIdentifier(selector) ? named(selector.simpleName) : undefined;
|
|
1511
|
+
if (value !== undefined) return {value};
|
|
1512
|
+
// A name that isn't a constant string may hold a component or props, which only its type tells apart
|
|
1513
|
+
if (TypedTree.getType(selector) !== Type.Primitive.String || isIdentifier(selector) && nested.has(selector.simpleName)) return undefined;
|
|
1514
|
+
return isIdentifier(selector) || selector.kind === J.Kind.FieldAccess ? {unread: await printed(selector)} : undefined;
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1383
1517
|
/** The string a template of `const` strings holds, from the test or the modules it imports them from. */
|
|
1384
1518
|
private constantString(node: J): string | undefined {
|
|
1385
1519
|
const parts = stringParts(node);
|