@openrewrite/recipes-react 0.19.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/i18n/translate-hard-coded-strings.d.ts +67 -0
- package/dist/i18n/translate-hard-coded-strings.d.ts.map +1 -0
- package/dist/i18n/translate-hard-coded-strings.js +439 -0
- package/dist/i18n/translate-hard-coded-strings.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +10 -1
- package/dist/index.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 +64 -4
- package/dist/search/find-enzyme-usage.js.map +1 -1
- package/dist/search/find-hard-coded-strings.d.ts +110 -0
- package/dist/search/find-hard-coded-strings.d.ts.map +1 -0
- package/dist/search/find-hard-coded-strings.js +987 -0
- package/dist/search/find-hard-coded-strings.js.map +1 -0
- package/dist/search/find-missing-use-client-directive.d.ts +2 -0
- package/dist/search/find-missing-use-client-directive.d.ts.map +1 -1
- package/dist/search/find-missing-use-client-directive.js +1 -0
- package/dist/search/find-missing-use-client-directive.js.map +1 -1
- package/dist/testing/enzyme-portals.d.ts +3 -5
- package/dist/testing/enzyme-portals.d.ts.map +1 -1
- package/dist/testing/enzyme-portals.js +8 -39
- package/dist/testing/enzyme-portals.js.map +1 -1
- package/dist/testing/enzyme-render-blockers.d.ts +10 -0
- package/dist/testing/enzyme-render-blockers.d.ts.map +1 -0
- package/dist/testing/enzyme-render-blockers.js +119 -0
- package/dist/testing/enzyme-render-blockers.js.map +1 -0
- package/dist/testing/enzyme-shared-wrapper.d.ts +26 -0
- package/dist/testing/enzyme-shared-wrapper.d.ts.map +1 -0
- package/dist/testing/enzyme-shared-wrapper.js +213 -0
- package/dist/testing/enzyme-shared-wrapper.js.map +1 -0
- 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 +355 -16
- package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
- package/dist/testing/enzyme-usage.d.ts +5 -1
- package/dist/testing/enzyme-usage.d.ts.map +1 -1
- package/dist/testing/enzyme-usage.js +48 -6
- package/dist/testing/enzyme-usage.js.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts +7 -1
- package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
- package/dist/testing/enzyme-wrapper-scope.js +24 -9
- package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
- package/dist/util/json-and-javascript.d.ts +4 -0
- package/dist/util/json-and-javascript.d.ts.map +1 -0
- package/dist/util/json-and-javascript.js +37 -0
- package/dist/util/json-and-javascript.js.map +1 -0
- package/dist/util/module-imports.d.ts +36 -0
- package/dist/util/module-imports.d.ts.map +1 -1
- package/dist/util/module-imports.js +216 -0
- package/dist/util/module-imports.js.map +1 -1
- package/dist/util/test-source.d.ts +2 -0
- package/dist/util/test-source.d.ts.map +1 -0
- package/dist/util/test-source.js +5 -0
- package/dist/util/test-source.js.map +1 -0
- package/dist/zustand/entry-store.d.ts +9 -0
- package/dist/zustand/entry-store.d.ts.map +1 -0
- package/dist/zustand/entry-store.js +136 -0
- package/dist/zustand/entry-store.js.map +1 -0
- package/dist/zustand/redux-stores.d.ts +15 -4
- package/dist/zustand/redux-stores.d.ts.map +1 -1
- package/dist/zustand/redux-stores.js +155 -10
- package/dist/zustand/redux-stores.js.map +1 -1
- package/dist/zustand/redux-to-zustand.d.ts +29 -5
- package/dist/zustand/redux-to-zustand.d.ts.map +1 -1
- package/dist/zustand/redux-to-zustand.js +629 -42
- package/dist/zustand/redux-to-zustand.js.map +1 -1
- package/dist/zustand/zustand-plan.d.ts +31 -6
- package/dist/zustand/zustand-plan.d.ts.map +1 -1
- package/dist/zustand/zustand-plan.js +320 -31
- package/dist/zustand/zustand-plan.js.map +1 -1
- package/package.json +1 -1
- package/src/i18n/translate-hard-coded-strings.ts +442 -0
- package/src/index.ts +7 -0
- package/src/search/find-enzyme-usage.ts +59 -6
- package/src/search/find-hard-coded-strings.ts +1006 -0
- package/src/search/find-missing-use-client-directive.ts +1 -1
- package/src/testing/enzyme-portals.ts +4 -44
- package/src/testing/enzyme-render-blockers.ts +113 -0
- package/src/testing/enzyme-shared-wrapper.ts +224 -0
- package/src/testing/enzyme-to-react-testing-library.ts +354 -19
- package/src/testing/enzyme-usage.ts +62 -5
- package/src/testing/enzyme-wrapper-scope.ts +24 -6
- package/src/util/json-and-javascript.ts +26 -0
- package/src/util/module-imports.ts +223 -0
- package/src/util/test-source.ts +2 -0
- package/src/zustand/entry-store.ts +131 -0
- package/src/zustand/redux-stores.ts +171 -11
- package/src/zustand/redux-to-zustand.ts +689 -48
- package/src/zustand/zustand-plan.ts +350 -29
|
@@ -19,7 +19,7 @@ const CLIENT_HOOKS = new Set([
|
|
|
19
19
|
const BROWSER_GLOBALS = new Set(['window', 'document', 'localStorage', 'sessionStorage', 'navigator']);
|
|
20
20
|
|
|
21
21
|
/** Directives are the string-literal statements at the top of a file. */
|
|
22
|
-
function hasDirective(cu: JS.CompilationUnit, directive: string): boolean {
|
|
22
|
+
export function hasDirective(cu: JS.CompilationUnit, directive: string): boolean {
|
|
23
23
|
for (const statement of cu.statements) {
|
|
24
24
|
let node: any = statement.element;
|
|
25
25
|
if (node.kind === JS.Kind.ExpressionStatement) node = node.expression;
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import {JS, JSX, moduleNameOf, walk} from "@openrewrite/rewrite/javascript";
|
|
2
2
|
import {isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
3
3
|
import {posix} from "path";
|
|
4
|
-
import {importBindings, isRelativeSpecifier,
|
|
4
|
+
import {exportedNames, importBindings, isRelativeSpecifier, packageName, Resolver} from "../util/module-imports";
|
|
5
|
+
|
|
6
|
+
export {packageName, resolver} from "../util/module-imports";
|
|
7
|
+
export type {Resolver} from "../util/module-imports";
|
|
5
8
|
import {ConstantParts, constantStrings} from "./enzyme-constant-strings";
|
|
6
9
|
|
|
7
10
|
/** An import a source renders: the module, and the export of it that a JSX tag in the source names. */
|
|
@@ -74,27 +77,6 @@ export function moduleFacts(cu: JS.CompilationUnit): ModuleFacts {
|
|
|
74
77
|
return {portal: callsCreatePortal(cu), rendered, reExports, declares, forwards, imports: imported, strings: constantStrings(cu)};
|
|
75
78
|
}
|
|
76
79
|
|
|
77
|
-
/** Each name a named export clause exports, to the name it has in the module it comes from. */
|
|
78
|
-
function exportedNames(clause: JS.NamedExports): Map<string, string> {
|
|
79
|
-
const names = new Map<string, string>();
|
|
80
|
-
for (const {element: exported} of clause.elements.elements) {
|
|
81
|
-
if (exported.kind !== JS.Kind.ExportSpecifier) continue;
|
|
82
|
-
const named = (exported as JS.ExportSpecifier).specifier;
|
|
83
|
-
if (isIdentifier(named)) names.set(named.simpleName, named.simpleName);
|
|
84
|
-
if (named.kind === JS.Kind.Alias && isIdentifier((named as JS.Alias).alias)) {
|
|
85
|
-
const property = (named as JS.Alias).propertyName.element;
|
|
86
|
-
names.set(((named as JS.Alias).alias as J.Identifier).simpleName,
|
|
87
|
-
isIdentifier(property) ? property.simpleName : String((property as J.Literal).value));
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
return names;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/** Where module specifiers of a source resolve: relative ones as Node resolves them, bare ones through a `baseUrl` alias. */
|
|
94
|
-
export interface Resolver {
|
|
95
|
-
(from: string, specifier: string): string | undefined;
|
|
96
|
-
}
|
|
97
|
-
|
|
98
80
|
/**
|
|
99
81
|
* Whether the export `name` of the source at `path` may render into a portal: the source calls
|
|
100
82
|
* `createPortal`, renders a component imported from a source whose export may, or re-exports `name`
|
|
@@ -162,28 +144,6 @@ export function packagePortal(module: string, name: string): boolean {
|
|
|
162
144
|
return exports.has(subpath !== "" && name === "default" ? subpath.split("/")[0] : name);
|
|
163
145
|
}
|
|
164
146
|
|
|
165
|
-
/** The package a bare module specifier names, such as `@scope/name` for `@scope/name/sub`. */
|
|
166
|
-
export function packageName(specifier: string): string {
|
|
167
|
-
const parts = specifier.split("/");
|
|
168
|
-
return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
/**
|
|
172
|
-
* Resolves relative specifiers among the scanned sources, and a bare one that no enclosing package
|
|
173
|
-
* declares from each of `roots`, the way a `baseUrl` of the package or the repository resolves it.
|
|
174
|
-
*/
|
|
175
|
-
export function resolver(modules: Modules, roots: readonly string[], declares: (name: string) => boolean): Resolver {
|
|
176
|
-
return (from, specifier) => {
|
|
177
|
-
const relative = resolveRelative(from, specifier, modules);
|
|
178
|
-
if (relative || isRelativeSpecifier(specifier) || specifier.startsWith("node:") || declares(packageName(specifier))) return relative;
|
|
179
|
-
for (const root of roots) {
|
|
180
|
-
const aliased = resolveRelative(posix.join(root || ".", "_"), `./${specifier}`, modules);
|
|
181
|
-
if (aliased) return aliased;
|
|
182
|
-
}
|
|
183
|
-
return undefined;
|
|
184
|
-
};
|
|
185
|
-
}
|
|
186
|
-
|
|
187
147
|
export interface PortalContext {
|
|
188
148
|
/** The test source. */
|
|
189
149
|
sourcePath: string;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import {Cursor, TreePrinters} from "@openrewrite/rewrite";
|
|
2
|
+
import {JS} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {J} from "@openrewrite/rewrite/java";
|
|
4
|
+
import {eventKind, selectorKind} from "../search/find-enzyme-usage";
|
|
5
|
+
import {migrationReason} from "./enzyme-usage";
|
|
6
|
+
|
|
7
|
+
/** Why the converter kept a render it analyzed on Enzyme, other than a use of its wrapper. */
|
|
8
|
+
export type RenderGate = "setProps" | "rootStyles" | "shallow" | "portal";
|
|
9
|
+
|
|
10
|
+
// The methods of Enzyme's wrappers, past which a chain reads what one returned, such as a DOM node
|
|
11
|
+
const ENZYME_WRAPPER_METHODS = new Set(["at", "childAt", "children", "closest", "contains", "containsAllMatchingElements",
|
|
12
|
+
"containsAnyMatchingElements", "containsMatchingElement", "context", "debug", "dive", "every", "everyWhere", "exists", "filter",
|
|
13
|
+
"filterWhere", "find", "findWhere", "first", "forEach", "get", "getDOMNode", "getElement", "getElements", "getNode", "getNodes",
|
|
14
|
+
"hasClass", "hostNodes", "html", "instance", "invoke", "is", "isEmptyRender", "key", "last", "map", "matchesElement", "name",
|
|
15
|
+
"not", "parent", "parents", "prop", "props", "reduce", "reduceRight", "ref", "render", "renderProp", "root", "setContext",
|
|
16
|
+
"setProps", "setState", "shallow", "simulate", "simulateError", "slice", "some", "someWhere", "state", "tap", "text", "type",
|
|
17
|
+
"unmount", "update"]);
|
|
18
|
+
|
|
19
|
+
// Calls that return another wrapper, which a variable then holds as Enzyme found it
|
|
20
|
+
const WRAPPER_RESULTS = new Set(["find", "at", "first", "last", "children", "childAt", "filter", "filterWhere", "findWhere",
|
|
21
|
+
"hostNodes", "closest", "parent", "parents", "dive", "not", "slice", "getElements", "getNodes"]);
|
|
22
|
+
|
|
23
|
+
const PASSED = "Blocked by a wrapper passed on: the recipe converts a wrapper only where each use is a read in the test itself. " +
|
|
24
|
+
"Inline what the helper reads here, or change the helper to take the element RTL queried, such as `container.querySelector(selector)`.";
|
|
25
|
+
const STORED = "Blocked by a stored find: Enzyme's found wrapper keeps the render as it was, while an RTL element is live. " +
|
|
26
|
+
"Query the element where each assertion reads it, such as `container.querySelector(selector)`, rather than keeping the found wrapper in a variable.";
|
|
27
|
+
const UNMOUNTED = "Blocked by a read after unmount: RTL's container is empty once the render unmounts. " +
|
|
28
|
+
"Assert before calling `unmount()`, or render again for what comes after.";
|
|
29
|
+
const FIND_HERE = "Blocked by `find`: Enzyme and the DOM can match different elements for this selector where it stands, " +
|
|
30
|
+
"as positions into matches of a selector without a tag in each part, or a part a component's props can match. " +
|
|
31
|
+
"Name the tag in each part of the selector, or call `hostNodes()` before taking a position.";
|
|
32
|
+
const SIMULATE_HERE = "Blocked by `simulate`: `fireEvent` doesn't dispatch this event as Enzyme does here, " +
|
|
33
|
+
"because React 15 and 16 need a render attached to the document, a click runs a link's or form control's default action, " +
|
|
34
|
+
"or the call isn't a statement of its own. Fire it as a statement on the element, or with `userEvent` where the default action is wanted.";
|
|
35
|
+
const GATES: Readonly<Record<RenderGate, string>> = {
|
|
36
|
+
setProps: "Blocked by `setProps`: the recipe writes `rerender` only for props it can merge into the element as written. " +
|
|
37
|
+
"Call `rerender` with the whole element and its new props.",
|
|
38
|
+
shallow: "Blocked by shallow rendering: the component renders other components or runs effects, which `shallow` leaves out and RTL's `render` runs. " +
|
|
39
|
+
"Render it with `render` and assert on what the whole tree renders. Where a test relies on a child not rendering, `jest.mock` that child's module with a stub.",
|
|
40
|
+
portal: "Blocked by a portal: a component it renders may render into a portal, which RTL renders outside the container. " +
|
|
41
|
+
"Query `screen` or `baseElement` for that content instead of the wrapper.",
|
|
42
|
+
rootStyles: "Blocked by root styles: a component of this package adds its `<style>` to the document root, which RTL's detached container lacks. " +
|
|
43
|
+
"Render without the `container` option, so the render is attached to the document, before reading text or markup."
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** Why the converter leaves every render of a source on Enzyme. */
|
|
47
|
+
export type FileGate = "react" | "rtl" | "rtlMissing" | "commonjs";
|
|
48
|
+
|
|
49
|
+
const FILES: Readonly<Record<FileGate, string>> = {
|
|
50
|
+
react: "Blocked for this file by its React: the recipe converts packages on React and React DOM 15.5 to 18, of the same major. " +
|
|
51
|
+
"On React 19, migrate the file by hand to RTL 16's `render`, `screen` and `fireEvent`, following the file's other rows.",
|
|
52
|
+
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
|
+
"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 to its package, as the package manager declined the edit, " +
|
|
55
|
+
"or no package of the file declares Enzyme. Add `@testing-library/react` to the package that declares Enzyme, then run the recipe again.",
|
|
56
|
+
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
|
+
};
|
|
58
|
+
|
|
59
|
+
export function blockedByFile(gate: FileGate): string {
|
|
60
|
+
return FILES[gate];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The suggested action for a render that the uses at `references` keep on Enzyme, naming the first of them. */
|
|
64
|
+
export async function blockedByUses(references: {cursor: Cursor, unmounted: boolean}[]): Promise<string> {
|
|
65
|
+
const [first] = references;
|
|
66
|
+
const {top, calls} = chainOf(first.cursor);
|
|
67
|
+
const action = first.unmounted ? UNMOUNTED : actionFor(top, calls, first.cursor);
|
|
68
|
+
const printed = (await TreePrinters.printer(JS.Kind.CompilationUnit).print(top)).trim().replace(/\s+/g, " ");
|
|
69
|
+
const snippet = printed.length > 80 ? `${printed.slice(0, 77)}...` : printed;
|
|
70
|
+
return `${action} ${references.length > 1 ? `First of ${references.length} uses that keep it on Enzyme` : "The use"}: \`${snippet}\``;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function blockedByGate(gate: RenderGate): string {
|
|
74
|
+
return GATES[gate];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The calls and accesses on the wrapper at `reference`, outermost last. */
|
|
78
|
+
function chainOf(reference: Cursor): {top: J, calls: J.MethodInvocation[]} {
|
|
79
|
+
let top = reference.value as J;
|
|
80
|
+
const calls: J.MethodInvocation[] = [];
|
|
81
|
+
for (let c = reference.parentTree(); c; c = c.parentTree()) {
|
|
82
|
+
const node = c.value as J;
|
|
83
|
+
if (node.kind === J.Kind.MethodInvocation && (node as J.MethodInvocation).select?.element === top) calls.push(node as J.MethodInvocation);
|
|
84
|
+
else if (!(node.kind === J.Kind.FieldAccess && (node as J.FieldAccess).target === top) &&
|
|
85
|
+
!(node.kind === J.Kind.ArrayAccess && (node as J.ArrayAccess).indexed === top)) break;
|
|
86
|
+
top = node;
|
|
87
|
+
}
|
|
88
|
+
return {top, calls};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function actionFor(top: J, calls: J.MethodInvocation[], reference: Cursor): string {
|
|
92
|
+
if (calls.length === 0) return PASSED;
|
|
93
|
+
let parent = reference.parentTree();
|
|
94
|
+
while (parent && parent.value !== top) parent = parent.parentTree();
|
|
95
|
+
const holder = parent?.parentTree()?.value as J | undefined;
|
|
96
|
+
// A component selector has no DOM query, whatever reads its matches
|
|
97
|
+
const component = calls.find(call => call.name.simpleName === "find" && selectorKind("find", call.arguments.elements[0]?.element) === "component");
|
|
98
|
+
const enzymeCalls = calls.filter(call => ENZYME_WRAPPER_METHODS.has(call.name.simpleName));
|
|
99
|
+
const last = enzymeCalls[enzymeCalls.length - 1] ?? calls[calls.length - 1];
|
|
100
|
+
if (!component && WRAPPER_RESULTS.has(last.name.simpleName)) {
|
|
101
|
+
if (holder?.kind === J.Kind.NamedVariable || holder?.kind === J.Kind.Assignment) return STORED;
|
|
102
|
+
if (last.name.simpleName !== "find") return PASSED;
|
|
103
|
+
}
|
|
104
|
+
const blocking = component ?? last;
|
|
105
|
+
const api = blocking.name.simpleName;
|
|
106
|
+
const args = blocking.arguments.elements.map(argument => argument.element);
|
|
107
|
+
const selector = selectorKind(api, args[0]);
|
|
108
|
+
const event = eventKind(api, args);
|
|
109
|
+
// Read on its own, a DOM selector or a plain event converts, so here it is where it stands that keeps it
|
|
110
|
+
if (selector === "dom") return FIND_HERE;
|
|
111
|
+
if (event === "event") return SIMULATE_HERE;
|
|
112
|
+
return `Blocked by \`${api}\`: ${migrationReason(api, selector, event).suggestedAction}`;
|
|
113
|
+
}
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import {Cursor, randomId} from "@openrewrite/rewrite";
|
|
2
|
+
import {JS, referencesOf} from "@openrewrite/rewrite/javascript";
|
|
3
|
+
import {isIdentifier, J} from "@openrewrite/rewrite/java";
|
|
4
|
+
import {mountedElement, variableCursor} from "./enzyme-wrapper-scope";
|
|
5
|
+
|
|
6
|
+
/** A `let` wrapper that each test of its block mounts for itself, and the `afterEach` that cleans it up, if there is one. */
|
|
7
|
+
export interface SharedWrapper {
|
|
8
|
+
declaration: J.VariableDeclarations;
|
|
9
|
+
name: string;
|
|
10
|
+
afterEach?: J;
|
|
11
|
+
/** The statements of the `afterEach` that unmount or clear the wrapper, or its expression body when that does. */
|
|
12
|
+
cleanup: ReadonlySet<string>;
|
|
13
|
+
/** The cleanup statements that unmount the wrapper. */
|
|
14
|
+
unmounts: ReadonlySet<string>;
|
|
15
|
+
/** The `wrapper = mount(...)` statements, each the first use of the wrapper in its test. */
|
|
16
|
+
assignments: ReadonlySet<string>;
|
|
17
|
+
/** The `wrapper = null` statements of the tests, after which a test no longer reads the wrapper. */
|
|
18
|
+
clears: ReadonlySet<string>;
|
|
19
|
+
/** The bodies of the tests that a `beforeEach` of their describe mounts the wrapper for, with that mount. */
|
|
20
|
+
hookMounts: ReadonlyMap<string, J.MethodInvocation>;
|
|
21
|
+
/** Those `beforeEach` mounts: the hook where it does nothing else, or else the mounting statement. */
|
|
22
|
+
hookRemovals: ReadonlySet<string>;
|
|
23
|
+
/** Each such hook, as it was, with the describe it is in, its mounting statement and the bodies of its tests. */
|
|
24
|
+
hooks: readonly SharedHook[];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface SharedHook {
|
|
28
|
+
owner: string;
|
|
29
|
+
hook: J;
|
|
30
|
+
/** The statements of its describe before it, and the prefix each statement of the describe had. */
|
|
31
|
+
before: readonly string[];
|
|
32
|
+
prefixes: ReadonlyMap<string, J["prefix"]>;
|
|
33
|
+
mounting: string;
|
|
34
|
+
tests: readonly string[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** A copy of a tree with new ids, which a tree copied into several places needs, sharing its types. */
|
|
38
|
+
export function withNewIds<T>(node: T): T {
|
|
39
|
+
if (Array.isArray(node)) return node.map(withNewIds) as T;
|
|
40
|
+
if (node === null || typeof node !== "object") return node;
|
|
41
|
+
const kind = (node as any).kind;
|
|
42
|
+
if (typeof kind === "string" && kind.startsWith("org.openrewrite.java.tree.JavaType")) return node;
|
|
43
|
+
const copy: any = {};
|
|
44
|
+
for (const [key, value] of Object.entries(node)) {
|
|
45
|
+
copy[key] = key === "id" && typeof value === "string" ? randomId() :
|
|
46
|
+
key === "type" || key === "methodType" || key === "fieldType" || key === "variableType" ? value : withNewIds(value);
|
|
47
|
+
}
|
|
48
|
+
return copy;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function describeBody(statement: J): J.Block | undefined {
|
|
52
|
+
const call = expressionOf(statement);
|
|
53
|
+
if (call.kind !== J.Kind.MethodInvocation) return undefined;
|
|
54
|
+
const body = callback(call as J.MethodInvocation, ["describe"])?.body;
|
|
55
|
+
return body?.kind === J.Kind.Block ? body as J.Block : undefined;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function expressionOf(statement: J): J {
|
|
59
|
+
return statement.kind === JS.Kind.ExpressionStatement ? (statement as JS.ExpressionStatement).expression : statement;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function callback(call: J.MethodInvocation, names: readonly string[]): J.Lambda | undefined {
|
|
63
|
+
if (call.select || !names.includes(call.name.simpleName)) return undefined;
|
|
64
|
+
// A hook takes its function first, a test or describe after its name
|
|
65
|
+
const argument = call.arguments.elements[names[0] === "afterEach" || names[0] === "beforeEach" ? 0 : 1]?.element;
|
|
66
|
+
return argument?.kind === JS.Kind.ArrowFunction ? (argument as JS.ArrowFunction).lambda : undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function named(node: J | undefined, name: string): boolean {
|
|
70
|
+
return node !== undefined && isIdentifier(node) && node.simpleName === name;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** `wrapper.unmount()` or `wrapper?.unmount()`. */
|
|
74
|
+
function unmountOf(node: J | undefined, name: string): boolean {
|
|
75
|
+
if (node?.kind !== J.Kind.MethodInvocation) return false;
|
|
76
|
+
const call = node as J.MethodInvocation;
|
|
77
|
+
return call.name.simpleName === "unmount" && named(call.select?.element, name) &&
|
|
78
|
+
call.arguments.elements.every(argument => argument.element.kind === J.Kind.Empty);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** `wrapper = null` or `wrapper = undefined`. */
|
|
82
|
+
function clearOf(node: J, name: string): boolean {
|
|
83
|
+
if (node.kind !== J.Kind.Assignment) return false;
|
|
84
|
+
const {variable, assignment} = node as J.Assignment;
|
|
85
|
+
const value = assignment.element;
|
|
86
|
+
// NOTE: a `null` literal from the RPC host carries no value, only its source
|
|
87
|
+
return named(variable, name) && (value.kind === J.Kind.Literal && (value as J.Literal).valueSource === "null" || named(value, "undefined"));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** An unmount of the wrapper, alone or under `if (wrapper)`, with or without braces. */
|
|
91
|
+
function unmountStatement(statement: J, name: string): boolean {
|
|
92
|
+
if (statement.kind !== J.Kind.If) return unmountOf(expressionOf(statement), name);
|
|
93
|
+
const guard = statement as J.If;
|
|
94
|
+
if (guard.elsePart || !named(guard.ifCondition.tree.element, name)) return false;
|
|
95
|
+
let then: J = guard.thenPart.element;
|
|
96
|
+
if (then.kind === J.Kind.Block) {
|
|
97
|
+
const statements = (then as J.Block).statements;
|
|
98
|
+
if (statements.length !== 1) return false;
|
|
99
|
+
then = statements[0].element;
|
|
100
|
+
}
|
|
101
|
+
return unmountOf(expressionOf(then), name);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* A wrapper declared without a value whose every use is in a test, of the same block or a describe within it, that
|
|
106
|
+
* starts by mounting it, as in `wrapper = mount(<Panel />);`, in a `beforeEach` that ends by mounting it for the tests
|
|
107
|
+
* of its describe, or in the `afterEach` statements that unmount or clear it. Each test's wrapper is then its own,
|
|
108
|
+
* which a `const` in the test declares as well, and RTL unmounts every render after each test.
|
|
109
|
+
*/
|
|
110
|
+
export function sharedWrapper(block: Cursor, statement: J): SharedWrapper | undefined {
|
|
111
|
+
if (statement.kind !== J.Kind.VariableDeclarations) return undefined;
|
|
112
|
+
const declaration = statement as J.VariableDeclarations;
|
|
113
|
+
if (declaration.variables.length !== 1 || declaration.leadingAnnotations.length > 0 ||
|
|
114
|
+
!declaration.modifiers.some(modifier => modifier.keyword === "let")) return undefined;
|
|
115
|
+
const variable = declaration.variables[0].element;
|
|
116
|
+
if (!isIdentifier(variable.name) || variable.initializer) return undefined;
|
|
117
|
+
const name = variable.name.simpleName;
|
|
118
|
+
let afterEach: J | undefined;
|
|
119
|
+
const cleanup = new Set<string>();
|
|
120
|
+
const unmounts = new Set<string>();
|
|
121
|
+
const assignments = new Set<string>();
|
|
122
|
+
const clears = new Set<string>();
|
|
123
|
+
const mounted = new Set<string>();
|
|
124
|
+
const cleared = new Set<string>();
|
|
125
|
+
// The describes whose tests mount the wrapper themselves, and those whose `beforeEach` mounts it
|
|
126
|
+
const ownMounts = new Set<string>();
|
|
127
|
+
const hooks = new Map<string, {owner: J.Block, hook: J, mount: J.MethodInvocation, mounting: string, removal: string}>();
|
|
128
|
+
for (const reference of referencesOf(new Cursor(variable.name, variableCursor(block, declaration)), name, "value")) {
|
|
129
|
+
if (reference.identifier === variable.name) continue;
|
|
130
|
+
if (reference.declares) return undefined;
|
|
131
|
+
const trees: Cursor[] = [];
|
|
132
|
+
let c = reference.cursor.parentTree();
|
|
133
|
+
for (; c && c.value !== block.value; c = c.parentTree()) trees.push(c);
|
|
134
|
+
if (!c || trees.length === 0) return undefined;
|
|
135
|
+
// The statement of the block, or of the describes within it, that holds the reference
|
|
136
|
+
let level = trees.length - 1;
|
|
137
|
+
let owner = block.value as J.Block;
|
|
138
|
+
for (let body = describeBody(trees[level].value as J); body; body = describeBody(trees[level].value as J)) {
|
|
139
|
+
const at = trees.findIndex(tree => tree.value === body);
|
|
140
|
+
if (at < 1) return undefined;
|
|
141
|
+
owner = body;
|
|
142
|
+
level = at - 1;
|
|
143
|
+
}
|
|
144
|
+
const top = trees[level].value as J;
|
|
145
|
+
const call = expressionOf(top);
|
|
146
|
+
if (call.kind !== J.Kind.MethodInvocation) return undefined;
|
|
147
|
+
const before = callback(call as J.MethodInvocation, ["beforeEach"]);
|
|
148
|
+
if (before) {
|
|
149
|
+
// The hook's last statement mounts the wrapper, so each test of the describe can mount it first instead
|
|
150
|
+
if (before.body.kind !== J.Kind.Block || hooks.has(owner.id) || ownMounts.has(owner.id) || !reference.writes) return undefined;
|
|
151
|
+
const body = before.body as J.Block;
|
|
152
|
+
const mounting = trees[trees.findIndex(tree => tree.value === body) - 1]?.value as J | undefined;
|
|
153
|
+
if (!mounting || mounting !== body.statements[body.statements.length - 1]?.element) return undefined;
|
|
154
|
+
const assignment = expressionOf(mounting);
|
|
155
|
+
if (assignment.kind !== J.Kind.Assignment || (assignment as J.Assignment).variable !== reference.identifier) return undefined;
|
|
156
|
+
const mount = (assignment as J.Assignment).assignment.element;
|
|
157
|
+
if (mount.kind !== J.Kind.MethodInvocation || !mountedElement(mount as J.MethodInvocation)) return undefined;
|
|
158
|
+
hooks.set(owner.id, {owner, hook: top, mount: mount as J.MethodInvocation, mounting: mounting.id, removal: body.statements.length === 1 ? top.id : mounting.id});
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
const after = callback(call as J.MethodInvocation, ["afterEach"]);
|
|
162
|
+
if (after) {
|
|
163
|
+
if (owner !== block.value || afterEach && afterEach !== top) return undefined;
|
|
164
|
+
afterEach = top;
|
|
165
|
+
// The statement of the callback the reference is in, or its expression body
|
|
166
|
+
const at = after.body.kind === J.Kind.Block ? trees.findIndex(tree => tree.value === after.body) - 1 : trees.findIndex(tree => tree.value === after.body);
|
|
167
|
+
const cleaning = trees[at]?.value as J | undefined;
|
|
168
|
+
if (!cleaning) return undefined;
|
|
169
|
+
if (unmountStatement(cleaning, name)) unmounts.add(cleaning.id);
|
|
170
|
+
else if (!clearOf(expressionOf(cleaning), name)) return undefined;
|
|
171
|
+
cleanup.add(cleaning.id);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
const test = callback(call as J.MethodInvocation, ["it", "test"]);
|
|
175
|
+
if (test?.body.kind !== J.Kind.Block) return undefined;
|
|
176
|
+
const body = test.body as J.Block;
|
|
177
|
+
if (hooks.has(owner.id)) {
|
|
178
|
+
if (reference.writes) return undefined;
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
if (cleared.has(body.id)) return undefined;
|
|
182
|
+
const assignment = trees[0].value as J;
|
|
183
|
+
const parent = trees[1]?.value as J | undefined;
|
|
184
|
+
const inBody = parent === body || parent?.kind === JS.Kind.ExpressionStatement && trees[2]?.value === body;
|
|
185
|
+
if (mounted.has(body.id)) {
|
|
186
|
+
if (!reference.writes) continue;
|
|
187
|
+
// Clearing the wrapper in a test is only for the afterEach, which no longer unmounts it
|
|
188
|
+
if (!inBody || !clearOf(assignment, name)) return undefined;
|
|
189
|
+
clears.add((parent === body ? assignment : parent!).id);
|
|
190
|
+
cleared.add(body.id);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
// The first use in a test mounts the wrapper as a statement of the test's body
|
|
194
|
+
if (!reference.writes || assignment.kind !== J.Kind.Assignment || (assignment as J.Assignment).variable !== reference.identifier || !inBody) return undefined;
|
|
195
|
+
const mount = (assignment as J.Assignment).assignment.element;
|
|
196
|
+
if (mount.kind !== J.Kind.MethodInvocation || !mountedElement(mount as J.MethodInvocation)) return undefined;
|
|
197
|
+
assignments.add(assignment.id);
|
|
198
|
+
mounted.add(body.id);
|
|
199
|
+
ownMounts.add(owner.id);
|
|
200
|
+
}
|
|
201
|
+
const hookMounts = new Map<string, J.MethodInvocation>();
|
|
202
|
+
const hookRemovals = new Set<string>();
|
|
203
|
+
const sharedHooks: SharedHook[] = [];
|
|
204
|
+
for (const {owner, hook, mount, mounting, removal} of hooks.values()) {
|
|
205
|
+
const tests: string[] = [];
|
|
206
|
+
// Every test of the describe mounts, as the hook ran for each, and no nested describe or later hook runs between
|
|
207
|
+
const statements = owner.statements.map(statement => statement.element);
|
|
208
|
+
for (const [i, statement] of statements.entries()) {
|
|
209
|
+
const call = expressionOf(statement);
|
|
210
|
+
if (call.kind !== J.Kind.MethodInvocation) continue;
|
|
211
|
+
if (describeBody(statement) || i > statements.indexOf(hook) && callback(call as J.MethodInvocation, ["beforeEach"])) return undefined;
|
|
212
|
+
const test = callback(call as J.MethodInvocation, ["it", "test"]);
|
|
213
|
+
if (!test) continue;
|
|
214
|
+
if (test.body.kind !== J.Kind.Block || (test.body as J.Block).statements.length === 0) return undefined;
|
|
215
|
+
hookMounts.set(test.body.id, mount);
|
|
216
|
+
tests.push(test.body.id);
|
|
217
|
+
}
|
|
218
|
+
hookRemovals.add(removal);
|
|
219
|
+
sharedHooks.push({owner: owner.id, hook, before: statements.slice(0, statements.indexOf(hook)).map(statement => statement.id),
|
|
220
|
+
prefixes: new Map(statements.map(statement => [statement.id, statement.prefix])), mounting, tests});
|
|
221
|
+
}
|
|
222
|
+
return assignments.size > 0 || hookMounts.size > 0 ?
|
|
223
|
+
{declaration, name, afterEach, cleanup, unmounts, assignments, clears, hookMounts, hookRemovals, hooks: sharedHooks} : undefined;
|
|
224
|
+
}
|