@openrewrite/recipes-react 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +9 -5
  4. package/dist/index.js.map +1 -1
  5. package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -1
  6. package/dist/migration/cra-to-vite/find-cra-config-blockers.js +3 -5
  7. package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
  8. package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -1
  9. package/dist/migration/cra-to-vite/update-react-app-env-types.js +5 -2
  10. package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -1
  11. package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
  12. package/dist/react18/replace-unmount-component-at-node.js +8 -1
  13. package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
  14. package/dist/react19/find-legacy-context-api.d.ts.map +1 -1
  15. package/dist/react19/find-legacy-context-api.js +21 -38
  16. package/dist/react19/find-legacy-context-api.js.map +1 -1
  17. package/dist/{react18 → react19}/remove-unstable-batched-updates.d.ts +2 -2
  18. package/dist/react19/remove-unstable-batched-updates.d.ts.map +1 -0
  19. package/dist/react19/remove-unstable-batched-updates.js +295 -0
  20. package/dist/react19/remove-unstable-batched-updates.js.map +1 -0
  21. package/dist/react19/replace-default-props.d.ts +1 -0
  22. package/dist/react19/replace-default-props.d.ts.map +1 -1
  23. package/dist/react19/replace-default-props.js +198 -151
  24. package/dist/react19/replace-default-props.js.map +1 -1
  25. package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
  26. package/dist/react19/replace-react-shallow-renderer.js +10 -25
  27. package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
  28. package/dist/refactoring/class-to-functional.d.ts.map +1 -1
  29. package/dist/refactoring/class-to-functional.js +2 -0
  30. package/dist/refactoring/class-to-functional.js.map +1 -1
  31. package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
  32. package/dist/refactoring/create-class-to-es6.js +14 -49
  33. package/dist/refactoring/create-class-to-es6.js.map +1 -1
  34. package/dist/search/find-function-component-default-props.d.ts.map +1 -1
  35. package/dist/search/find-function-component-default-props.js +6 -15
  36. package/dist/search/find-function-component-default-props.js.map +1 -1
  37. package/dist/search/find-redux-stores.d.ts +12 -0
  38. package/dist/search/find-redux-stores.d.ts.map +1 -0
  39. package/dist/search/find-redux-stores.js +87 -0
  40. package/dist/search/find-redux-stores.js.map +1 -0
  41. package/dist/simplify-object-pattern-property.d.ts.map +1 -1
  42. package/dist/simplify-object-pattern-property.js +14 -21
  43. package/dist/simplify-object-pattern-property.js.map +1 -1
  44. package/dist/simplify-react-imports.d.ts.map +1 -1
  45. package/dist/simplify-react-imports.js +10 -59
  46. package/dist/simplify-react-imports.js.map +1 -1
  47. package/dist/testing/enzyme-to-react-testing-library.d.ts +10 -1
  48. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  49. package/dist/testing/enzyme-to-react-testing-library.js +79 -22
  50. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  51. package/dist/testing/enzyme-wrapper-scope.d.ts +3 -1
  52. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  53. package/dist/testing/enzyme-wrapper-scope.js +10 -7
  54. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  55. package/dist/util/java-recipe-proxy.d.ts +2 -0
  56. package/dist/util/java-recipe-proxy.d.ts.map +1 -1
  57. package/dist/util/java-recipe-proxy.js +14 -2
  58. package/dist/util/java-recipe-proxy.js.map +1 -1
  59. package/dist/util/reindent.d.ts +5 -0
  60. package/dist/util/reindent.d.ts.map +1 -0
  61. package/dist/util/reindent.js +44 -0
  62. package/dist/util/reindent.js.map +1 -0
  63. package/dist/zustand/redux-stores.d.ts +74 -0
  64. package/dist/zustand/redux-stores.d.ts.map +1 -0
  65. package/dist/zustand/redux-stores.js +402 -0
  66. package/dist/zustand/redux-stores.js.map +1 -0
  67. package/dist/zustand/redux-to-zustand.d.ts +76 -0
  68. package/dist/zustand/redux-to-zustand.d.ts.map +1 -0
  69. package/dist/zustand/redux-to-zustand.js +653 -0
  70. package/dist/zustand/redux-to-zustand.js.map +1 -0
  71. package/dist/zustand/zustand-plan.d.ts +96 -0
  72. package/dist/zustand/zustand-plan.d.ts.map +1 -0
  73. package/dist/zustand/zustand-plan.js +822 -0
  74. package/dist/zustand/zustand-plan.js.map +1 -0
  75. package/package.json +1 -1
  76. package/src/index.ts +7 -3
  77. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +3 -5
  78. package/src/migration/cra-to-vite/update-react-app-env-types.ts +3 -3
  79. package/src/react18/replace-unmount-component-at-node.ts +13 -2
  80. package/src/react19/find-legacy-context-api.ts +21 -42
  81. package/src/react19/remove-unstable-batched-updates.ts +301 -0
  82. package/src/react19/replace-default-props.ts +212 -159
  83. package/src/react19/replace-react-shallow-renderer.ts +13 -36
  84. package/src/refactoring/class-to-functional.ts +3 -1
  85. package/src/refactoring/create-class-to-es6.ts +12 -63
  86. package/src/search/find-function-component-default-props.ts +8 -10
  87. package/src/search/find-redux-stores.ts +76 -0
  88. package/src/simplify-object-pattern-property.ts +22 -49
  89. package/src/simplify-react-imports.ts +12 -66
  90. package/src/testing/enzyme-to-react-testing-library.ts +112 -27
  91. package/src/testing/enzyme-wrapper-scope.ts +15 -10
  92. package/src/util/java-recipe-proxy.ts +15 -2
  93. package/src/util/reindent.ts +35 -0
  94. package/src/zustand/redux-stores.ts +409 -0
  95. package/src/zustand/redux-to-zustand.ts +657 -0
  96. package/src/zustand/zustand-plan.ts +843 -0
  97. package/dist/react18/remove-unstable-batched-updates.d.ts.map +0 -1
  98. package/dist/react18/remove-unstable-batched-updates.js +0 -170
  99. package/dist/react18/remove-unstable-batched-updates.js.map +0 -1
  100. package/src/react18/remove-unstable-batched-updates.ts +0 -192
@@ -1,5 +1,5 @@
1
1
  import {Column, DataTable, ExecutionContext, foundSearchResult, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
- import {isVendoredOrBundled, JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
2
+ import {isVendoredOrBundled, JavaScriptVisitor, JS, referencesOf} from "@openrewrite/rewrite/javascript";
3
3
  import {J} from "@openrewrite/rewrite/java";
4
4
  import {extendsReactComponentByName} from "../util/react-class";
5
5
 
@@ -41,25 +41,23 @@ export class FindFunctionComponentDefaultProps extends Recipe {
41
41
 
42
42
  return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
43
43
  private filePath = "";
44
- private classComponents = new Set<string>();
45
44
 
46
45
  override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
47
46
  this.filePath = cu.sourcePath ?? "";
48
- const classes = this.classComponents = new Set<string>();
49
- await new class extends JavaScriptVisitor<ExecutionContext> {
50
- protected override async visitClassDeclaration(decl: J.ClassDeclaration, c: ExecutionContext): Promise<J | undefined> {
51
- if (extendsReactComponentByName(decl)) classes.add(decl.name.simpleName);
52
- return super.visitClassDeclaration(decl, c);
53
- }
54
- }().visit(cu, ctx);
55
47
  return super.visitJsCompilationUnit(cu, ctx);
56
48
  }
57
49
 
50
+ /** Resolved rather than matched by name, so a parameter or local that shadows a class component still counts. */
51
+ private isClassComponent(name: string): boolean {
52
+ const declaration = referencesOf(this.cursor, name, 'value').find(r => r.declares)?.cursor.parent?.value;
53
+ return declaration?.kind === J.Kind.ClassDeclaration && extendsReactComponentByName(declaration as J.ClassDeclaration);
54
+ }
55
+
58
56
  override async visitFieldAccess(fieldAccess: J.FieldAccess, ctx: ExecutionContext): Promise<J | undefined> {
59
57
  const fa = await super.visitFieldAccess(fieldAccess, ctx) as J.FieldAccess;
60
58
  if (fa.name.element.simpleName !== 'defaultProps' || fa.target.kind !== J.Kind.Identifier) return fa;
61
59
  const receiver = (fa.target as J.Identifier).simpleName;
62
- if (!/^[A-Z]/.test(receiver) || this.classComponents.has(receiver)) return fa;
60
+ if (!/^[A-Z]/.test(receiver) || this.isClassComponent(receiver)) return fa;
63
61
  dataTable.insertRow(ctx, {filePath: this.filePath, component: receiver, upgradeStep: DEFAULT_PROPS_STEP});
64
62
  return foundSearchResult(fa, 'defaultProps') as J.FieldAccess;
65
63
  }
@@ -0,0 +1,76 @@
1
+ import {check, DataTable, ExecutionContext, foundSearchResult, not, ScanningRecipe, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {isVendoredOrBundled, JavaScriptVisitor, JS} from "@openrewrite/rewrite/javascript";
3
+ import {J} from "@openrewrite/rewrite/java";
4
+ import {
5
+ localSlices, REDUX_STORES_TABLE, ReduxStoreRow, SliceModule, storeFindings, storeFunctions, storeName, SUGGESTED_ACTIONS, TEST_SOURCE, ZUSTAND_GUIDE
6
+ } from "../zustand/redux-stores";
7
+
8
+ /**
9
+ * Inventories the Redux stores of a repository for a migration to zustand. A store is a candidate when it is a
10
+ * `configureStore` call whose `reducer` is an object of `createSlice` reducers, in the same source or imported from
11
+ * a relative module, and whose options are only `reducer`. Every other store gets a row for each reason it is not,
12
+ * such as a legacy `createStore`, custom middleware or a hand-written reducer. Stores are attributed by what the
13
+ * source imports from `redux` or `@reduxjs/toolkit`; namespace imports and `require` are not followed.
14
+ *
15
+ * Only the store's setup is checked; the components and modules that read or dispatch to it are not.
16
+ *
17
+ * @see https://zustand.docs.pmnd.rs/guides/migrating-to-zustand
18
+ */
19
+ export class FindReduxStores extends ScanningRecipe<Map<string, SliceModule>> {
20
+ readonly name = "org.openrewrite.react.search.find-redux-stores";
21
+ readonly displayName = "Find Redux stores";
22
+ readonly description = "Finds the Redux stores created with `createStore` or Redux Toolkit's `configureStore` and records whether each one's setup can move to zustand: a `configureStore` call whose `reducer` is an object of `createSlice` reducers without `extraReducers`, and no other option, is a candidate. Every other store is recorded with the reasons it is not, such as a legacy `createStore`, custom middleware, enhancers, preloaded state or a hand-written reducer. The components and modules that use a store are not checked.";
23
+
24
+ private readonly stores = new DataTable<ReduxStoreRow>(
25
+ REDUX_STORES_TABLE, "Redux stores",
26
+ "The Redux stores of the repository and whether each one's setup can move to zustand, with one row for each reason it can't.",
27
+ ReduxStoreRow
28
+ );
29
+
30
+ initialValue(): Map<string, SliceModule> {
31
+ return new Map();
32
+ }
33
+
34
+ async scanner(modules: Map<string, SliceModule>): Promise<TreeVisitor<any, ExecutionContext>> {
35
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
36
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit): Promise<J | undefined> {
37
+ const {reducers, slices} = localSlices(cu);
38
+ // Every source is kept, so that a relative import resolves to the file Node would load
39
+ modules.set(cu.sourcePath, {reducers, slices});
40
+ return cu;
41
+ }
42
+ }());
43
+ }
44
+
45
+ async editorWithData(modules: Map<string, SliceModule>): Promise<TreeVisitor<any, ExecutionContext>> {
46
+ const stores = this.stores;
47
+ return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
48
+ private cu?: JS.CompilationUnit;
49
+ private functions = {legacy: new Set<string>(), configure: new Set<string>()};
50
+
51
+ override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
52
+ this.functions = storeFunctions(cu);
53
+ if (this.functions.legacy.size === 0 && this.functions.configure.size === 0) return cu;
54
+ this.cu = cu;
55
+ return super.visitJsCompilationUnit(cu, ctx);
56
+ }
57
+
58
+ override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
59
+ const visited = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
60
+ const found = storeFindings(method, this.cu!, modules, this.functions);
61
+ if (!found) return visited;
62
+ const {api, findings} = found;
63
+ const cu = this.cu!;
64
+ const rows = findings.length === 0 ? [{reason: "SLICE_STORE", detail: ""}] : findings;
65
+ for (const {reason, detail} of rows) {
66
+ stores.insertRow(ctx, {
67
+ sourcePath: cu.sourcePath, store: storeName(this.cursor), api,
68
+ status: findings.length === 0 ? "CANDIDATE" : "REVIEW", reason, detail,
69
+ testSource: TEST_SOURCE.test(cu.sourcePath), suggestedAction: SUGGESTED_ACTIONS[reason]
70
+ });
71
+ }
72
+ return foundSearchResult(visited, `Redux store: ${rows.map(row => row.reason).join(", ")}. See ${ZUSTAND_GUIDE}`);
73
+ }
74
+ }());
75
+ }
76
+ }
@@ -1,7 +1,6 @@
1
- import {ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
1
+ import {ExecutionContext, Recipe, TreeVisitor, check, mapAsync, not, updateIfChanged} from "@openrewrite/rewrite";
2
2
  import {JavaScriptVisitor, JS, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
3
3
  import {J} from "@openrewrite/rewrite/java";
4
- import {create} from "mutative";
5
4
 
6
5
  /**
7
6
  * Simplifies object pattern properties where the key and value have the same name.
@@ -19,55 +18,29 @@ export class SimplifyObjectPatternProperty extends Recipe {
19
18
  async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
20
19
  return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
21
20
  protected async visitObjectBindingPattern(pattern: JS.ObjectBindingPattern, p: ExecutionContext): Promise<J | undefined> {
22
- // First, recursively visit children
23
21
  const visited = await super.visitObjectBindingPattern(pattern, p) as JS.ObjectBindingPattern;
24
-
25
- // Now simplify any properties where key === value
26
- const simplifiedBindings = visited.bindings.elements.map(right => {
27
- const element = right.element;
28
-
29
- // Check if this is a property assignment pattern (e.g., { x: x })
30
- if (element.kind === JS.Kind.BindingElement) {
31
- const binding = element as JS.BindingElement;
32
-
33
- // Check if the property name is an identifier
34
- if (binding.propertyName && binding.propertyName.element.kind === J.Kind.Identifier) {
35
- const propName = (binding.propertyName.element as J.Identifier).simpleName;
36
-
37
- // Check if the assignment is also an identifier with the same name
38
- if (binding.name && binding.name.kind === J.Kind.Identifier) {
39
- const assignmentName = (binding.name as J.Identifier).simpleName;
40
-
41
- // If they match, simplify to just the identifier
42
- if (propName === assignmentName) {
43
- // Create a new binding element with propertyName set to undefined (shorthand syntax)
44
- // Also need to update the name's prefix to remove extra spacing
45
- return {
46
- ...right,
47
- element: {
48
- ...binding,
49
- propertyName: undefined,
50
- name: {
51
- ...binding.name,
52
- prefix: binding.propertyName!.element.prefix
53
- }
54
- }
55
- } as J.RightPadded<JS.BindingElement>;
56
- }
22
+ return updateIfChanged(visited, {
23
+ bindings: updateIfChanged(visited.bindings, {
24
+ elements: await mapAsync(visited.bindings.elements, async right => {
25
+ const binding = right.element;
26
+ if (binding.kind !== JS.Kind.BindingElement) {
27
+ return right;
57
28
  }
58
- }
59
- }
60
-
61
- return right;
62
- });
63
-
64
- if (simplifiedBindings.every((binding, i) => binding === visited.bindings.elements[i])) {
65
- return visited;
66
- }
67
-
68
- // Return the pattern with simplified bindings using Mutative
69
- return create(visited, draft => {
70
- draft.bindings.elements = simplifiedBindings;
29
+ const {propertyName, name} = binding as JS.BindingElement;
30
+ if (propertyName?.element.kind !== J.Kind.Identifier || name?.kind !== J.Kind.Identifier ||
31
+ (propertyName.element as J.Identifier).simpleName !== (name as J.Identifier).simpleName) {
32
+ return right;
33
+ }
34
+ return {
35
+ ...right,
36
+ element: {
37
+ ...binding,
38
+ propertyName: undefined,
39
+ name: {...name, prefix: propertyName.element.prefix}
40
+ }
41
+ } as J.RightPadded<JS.BindingElement>;
42
+ })
43
+ })
71
44
  });
72
45
  }
73
46
  }());
@@ -1,7 +1,7 @@
1
1
  import {ExecutionContext, Recipe, TreeVisitor, check, not} from "@openrewrite/rewrite";
2
- import {JavaScriptVisitor, maybeAddImport, isVendoredOrBundled} from "@openrewrite/rewrite/javascript";
2
+ import {JavaScriptVisitor, JS, maybeAddImport, isVendoredOrBundled, namesDeclaredIn} from "@openrewrite/rewrite/javascript";
3
3
  import {J} from "@openrewrite/rewrite/java";
4
- import {JS} from "@openrewrite/rewrite/javascript";
4
+ import {importBindings} from "./util/module-imports";
5
5
 
6
6
  /**
7
7
  * Common React hooks and utilities that can be imported directly instead of
@@ -100,24 +100,20 @@ export class SimplifyReactImports extends Recipe {
100
100
 
101
101
  async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
102
102
  return check(not(isVendoredOrBundled()), new class extends JavaScriptVisitor<ExecutionContext> {
103
- // Track which React exports we've used in this file
104
103
  private usedExports = new Set<string>();
105
- // Track locally defined identifiers to avoid naming conflicts
106
- private localIdentifiers = new Set<string>();
104
+ private declaredNames = new Set<string>();
107
105
 
108
106
  override async visitJsCompilationUnit(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<J | undefined> {
109
- // Reset tracking for each file
110
107
  this.usedExports = new Set<string>();
111
- this.localIdentifiers = new Set<string>();
112
-
113
- // First pass: collect all locally defined identifiers
114
- await this.collectLocalIdentifiers(cu, ctx);
108
+ // File-wide rather than in scope, as `maybeAddImport` aliases the import when any binding of the name is declared
109
+ this.declaredNames = new Set(namesDeclaredIn(cu));
110
+ for (const {local, name, module} of importBindings(cu)) {
111
+ if (module === 'react' && local === name) this.declaredNames.delete(local);
112
+ }
115
113
 
116
- // Second pass: visit and transform all React.xxx usages
117
- let result = await super.visitJsCompilationUnit(cu, ctx) as JS.CompilationUnit;
114
+ const result = await super.visitJsCompilationUnit(cu, ctx) as JS.CompilationUnit;
118
115
 
119
- // Second pass: add imports for all used exports
120
- // We set onlyIfReferenced: false since we already know these are used (we just transformed them)
116
+ // Already known to be referenced, since they were just unqualified
121
117
  for (const exportName of this.usedExports) {
122
118
  maybeAddImport(this, {module: "react", member: exportName, onlyIfReferenced: false});
123
119
  }
@@ -125,54 +121,6 @@ export class SimplifyReactImports extends Recipe {
125
121
  return result;
126
122
  }
127
123
 
128
- /**
129
- * Collect all locally defined identifiers to detect potential naming conflicts.
130
- * This includes variable declarations, function declarations, and non-React imports.
131
- */
132
- private async collectLocalIdentifiers(cu: JS.CompilationUnit, ctx: ExecutionContext): Promise<void> {
133
- const collector = new class extends JavaScriptVisitor<ExecutionContext> {
134
- constructor(private identifiers: Set<string>) {
135
- super();
136
- }
137
-
138
- override async visitVariableDeclarations(varDecl: J.VariableDeclarations, ctx: ExecutionContext): Promise<J | undefined> {
139
- for (const v of varDecl.variables) {
140
- const name = v.element.name;
141
- if (name.kind === J.Kind.Identifier) {
142
- this.identifiers.add((name as J.Identifier).simpleName);
143
- }
144
- }
145
- return super.visitVariableDeclarations(varDecl, ctx);
146
- }
147
-
148
- override async visitMethodDeclaration(method: J.MethodDeclaration, ctx: ExecutionContext): Promise<J | undefined> {
149
- this.identifiers.add(method.name.simpleName);
150
- return super.visitMethodDeclaration(method, ctx);
151
- }
152
-
153
- override async visitImportSpecifier(spec: JS.ImportSpecifier, ctx: ExecutionContext): Promise<J | undefined> {
154
- // Track named imports
155
- const specifier = spec.specifier;
156
-
157
- if (specifier.kind === JS.Kind.Alias) {
158
- // Aliased import: import { useState as myUseState }
159
- const alias = specifier as JS.Alias;
160
- const aliasIdent = alias.alias;
161
- if (aliasIdent.kind === J.Kind.Identifier) {
162
- this.identifiers.add((aliasIdent as J.Identifier).simpleName);
163
- }
164
- } else if (specifier.kind === J.Kind.Identifier) {
165
- // Direct import: import { useState }
166
- // We don't track these as conflicts since they're the imports we manage
167
- }
168
-
169
- return super.visitImportSpecifier(spec, ctx);
170
- }
171
- }(this.localIdentifiers);
172
-
173
- await collector.visit(cu, ctx);
174
- }
175
-
176
124
  override async visitMethodInvocation(method: J.MethodInvocation, ctx: ExecutionContext): Promise<J | undefined> {
177
125
  let m = await super.visitMethodInvocation(method, ctx) as J.MethodInvocation;
178
126
 
@@ -181,8 +129,7 @@ export class SimplifyReactImports extends Recipe {
181
129
  return m;
182
130
  }
183
131
 
184
- // Skip transformation if there's a local identifier with the same name
185
- if (this.localIdentifiers.has(methodName)) {
132
+ if (this.declaredNames.has(methodName)) {
186
133
  return m;
187
134
  }
188
135
 
@@ -220,8 +167,7 @@ export class SimplifyReactImports extends Recipe {
220
167
  return fa;
221
168
  }
222
169
 
223
- // Skip transformation if there's a local identifier with the same name
224
- if (this.localIdentifiers.has(memberName)) {
170
+ if (this.declaredNames.has(memberName)) {
225
171
  return fa;
226
172
  }
227
173
 
@@ -1,4 +1,5 @@
1
- import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, or, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
1
+ import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, or, RecipeRef, ScanningRecipe, SourceFile, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
2
+ import {isPlainText} from "@openrewrite/rewrite/text";
2
3
  import {AddDependencyOptions, autoFormat, Autodetect, capture, PrettierStyle, deconflict, findNodeResolutionResult, isTypeScript, isVendoredOrBundled, JavaScriptVisitor, JS, maybeRemoveImport, moduleBindings, namesUsedIn, pattern, raw, rewrite, scopeOf, StyleKind, Template, template, usesMethod} from "@openrewrite/rewrite/javascript";
3
4
  import {Expression, J} from "@openrewrite/rewrite/java";
4
5
  import {create} from "mutative";
@@ -18,13 +19,13 @@ import {analyzeWrapperScope, SIMULATED_EVENTS, idsWithin, innermostCall, mounted
18
19
 
19
20
  const RTL = "@testing-library/react";
20
21
 
21
- const REACT_RANGE = ">=16.9.0 <18";
22
+ const REACT_RANGE = ">=15.5.0 <18";
22
23
 
23
24
  const REACT_18_RANGE = ">=18.0.0 <19";
24
25
 
25
26
  const resolvingReact = (range: string) => [`react@${range}`, `react-dom@${range}`];
26
27
 
27
- /** RTL 12 supports React 16.9 to 17, so it goes where Enzyme is used with those. */
28
+ /** RTL 12 renders with React 15.5 to 17, through its own act polyfill before 16.8, so it goes where Enzyme is used with those. */
28
29
  const RTL_ADDITION: AddDependencyOptions = {
29
30
  packageName: RTL, version: "^12.1.5", scope: "devDependencies",
30
31
  onlyIfDeclaring: ["enzyme"], onlyIfResolving: resolvingReact(REACT_RANGE)
@@ -142,7 +143,7 @@ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
142
143
  export class AddTestingLibraryReact extends EnzymeTestDependency {
143
144
  readonly name = "org.openrewrite.react.migrate.add-testing-library-react";
144
145
  readonly displayName = "Add `@testing-library/react` where Enzyme tests are migrated";
145
- readonly description = "Adds `@testing-library/react` 12 as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 16.9 to 17.";
146
+ readonly description = "Adds `@testing-library/react` 12 as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 15.5 to 17.";
146
147
 
147
148
  constructor(forecast: ConversionForecast = {}) {
148
149
  super(RTL_ADDITION, forecast);
@@ -283,10 +284,16 @@ interface PackageDeclarations {
283
284
  reactDom: Declaration;
284
285
  rtl: Declaration;
285
286
  enzyme: boolean;
287
+ /** Its `name`, by which packages of the same repository depend on it. */
288
+ name: string | undefined;
289
+ /** For a workspace root, the package roots of its members, which share its `node_modules` and lockfile. */
290
+ members: ReadonlySet<string>;
286
291
  /** The names of every package it depends on, in any dependency section. */
287
292
  dependencies: ReadonlySet<string>;
288
293
  /** Whether its lockfile resolves a package that puts styles into the root node of a render's container. */
289
294
  rootStyles: boolean;
295
+ /** Whether its test toolchain parses `?.` and `??`: JavaScript through Babel 7.8+ or react-scripts 3.3+, TypeScript also through TypeScript 3.7+. */
296
+ optionalChaining: {js: boolean, ts: boolean};
290
297
  }
291
298
 
292
299
  /**
@@ -302,6 +309,16 @@ export function injectsRootStyles(packages: Packages, sourcePath: string): boole
302
309
  return [...packages.entries()].some(([root, declarations]) => sourcePath.startsWith(root) && declarations.rootStyles);
303
310
  }
304
311
 
312
+ /** Whether every package a test is in has a toolchain that parses optional chaining for it. */
313
+ export function parsesOptionalChaining(packages: Packages, sourcePath: string, typescript: boolean): boolean {
314
+ return [...packages.entries()].every(([root, {optionalChaining}]) => !sourcePath.startsWith(root) ||
315
+ (typescript ? optionalChaining.ts : optionalChaining.js));
316
+ }
317
+
318
+ /** A declared or resolved version below `major.minor`. */
319
+ const below = (version: Declaration, major: number, minor: number) => typeof version === "object" &&
320
+ (version.major < major || version.major === major && version.minor !== undefined && version.minor < minor);
321
+
305
322
  /** The reads of a whole container, which see what a component inserts into it besides what React renders. */
306
323
  const CONTAINER_READS: ReadonlySet<WrapperUse> = new Set<WrapperUse>(["text", "rootHtml", "snapshot"]);
307
324
 
@@ -314,8 +331,15 @@ interface Scanned {
314
331
  modules: Modules;
315
332
  /** The words of each source's strings, for the selectors whose ancestor compounds name no tag. */
316
333
  names: Map<string, SelectorNames>;
334
+ /** The tests whose stored Jest snapshots include Enzyme's `null` for an empty render. */
335
+ nullSnapshots: Set<string>;
317
336
  }
318
337
 
338
+ // REGEX: `<dir>/__snapshots__/<test file>.snap`, Jest's default location of a test file's snapshots
339
+ const SNAPSHOT_FILE = /^(.*?)__snapshots__\/([^/]+)\.snap$/;
340
+ // REGEX: a stored snapshot entry whose value is `null`
341
+ const NULL_SNAPSHOT = /^exports\[`.*`\] = `null`;$/m;
342
+
319
343
  /** A dry run of the editor: the package roots it takes RTL to have, and the sources it converts. */
320
344
  interface DryRun {
321
345
  landed: ReadonlySet<string>;
@@ -347,7 +371,8 @@ const READS: Record<Render, {simulate: boolean, html: boolean, props: (props: Ex
347
371
  * The React major version the tests of a source file run with, or 0 where they cannot migrate. A
348
372
  * dependency the owning package does not declare comes from the nearest enclosing package that
349
373
  * does, where Node resolves it from. Where the run added RTL to the nearest package declaring
350
- * Enzyme, one of the `landed` package roots, it is there for every package within it.
374
+ * Enzyme, one of the `landed` package roots, it is there for every package within it, and for the
375
+ * workspace packages that take Enzyme from it as a dependency, as from a shared Jest preset.
351
376
  */
352
377
  export function reactMajor(packages: Packages, sourcePath: string, landed: ReadonlySet<string> = new Set()): number {
353
378
  return compatibility(packages, sourcePath, landed).react;
@@ -366,14 +391,14 @@ const HOVER_EVENTS = new Set(["mouseEnter", "mouseLeave", "mouseOver", "mouseOut
366
391
  /**
367
392
  * Which `simulate` calls can become `fireEvent` for a source file. On React 17, every supported event,
368
393
  * with an RTL whose `fireEvent.focus`, `blur`, `mouseEnter`, and `mouseLeave` also dispatch the events React 17
369
- * listens to, which RTL 10 does only from 10.4.9. On React 16.9+, which listens on the document rather than
394
+ * listens to, which RTL 10 does only from 10.4.9. On React 15 and 16, which listen on the document rather than
370
395
  * the root, every one but the hover events, in a render attached to the document.
371
396
  */
372
397
  export function simulatesEvents(packages: Packages, sourcePath: string, landed: ReadonlySet<string> = new Set()): SimulatedEvents {
373
398
  const {react, rtl} = compatibility(packages, sourcePath, landed);
374
399
  // React 18 listens on the root, as React 17 does
375
400
  if (react >= 17 && rtl >= 11) return {events: SIMULATED_EVENTS, attached: false};
376
- if (react === 16 && rtl >= 10) return {events: new Set([...SIMULATED_EVENTS].filter(event => !HOVER_EVENTS.has(event))), attached: true};
401
+ if ((react === 15 || react === 16) && rtl >= 10) return {events: new Set([...SIMULATED_EVENTS].filter(event => !HOVER_EVENTS.has(event))), attached: true};
377
402
  return {events: new Set(), attached: false};
378
403
  }
379
404
 
@@ -383,16 +408,18 @@ function compatibility(packages: Packages, sourcePath: string, landed: ReadonlyS
383
408
  const declared = (name: "react" | "reactDom" | "rtl", from = roots) =>
384
409
  from.map(root => packages.get(root)![name]).find(version => version !== undefined);
385
410
  const supportedReact = (version: Declaration): version is DeclaredVersion => typeof version === "object" &&
386
- (version.major === 17 || version.major === 18 || (version.major === 16 && version.minor !== undefined && version.minor >= 9));
411
+ ([16, 17, 18].includes(version.major) || version.major === 15 && version.minor !== undefined && version.minor >= 5);
387
412
  const react = declared("react");
388
413
  const rtl = declared("rtl");
389
414
  const enzyme = roots.findIndex(root => packages.get(root)!.enzyme);
390
- const enzymeReact = enzyme >= 0 ? declared("react", roots.slice(enzyme)) : undefined;
391
- const added = rtl === undefined && enzyme >= 0 && landed.has(roots[enzyme]) &&
392
- supportedReact(enzymeReact) && supportedReact(declared("reactDom", roots.slice(enzyme)));
415
+ // The package roots RTL goes to and resolves React from: those of the package declaring Enzyme
416
+ const enzymeRoots = enzyme >= 0 ? roots.slice(enzyme) : providerRoots(packages, roots);
417
+ const enzymeReact = enzymeRoots.length ? declared("react", enzymeRoots) : undefined;
418
+ const added = rtl === undefined && enzymeRoots.length > 0 && landed.has(enzymeRoots[0]) &&
419
+ supportedReact(enzymeReact) && supportedReact(declared("reactDom", enzymeRoots));
393
420
  // RTL renders with the React DOM it resolves from its own package
394
- const rtlRoot = added ? enzyme : roots.findIndex(root => packages.get(root)!.rtl !== undefined);
395
- const reactDom = declared("reactDom", roots.slice(Math.max(rtlRoot, 0))) ?? declared("reactDom");
421
+ const rtlRoot = roots.findIndex(root => packages.get(root)!.rtl !== undefined);
422
+ const reactDom = added ? declared("reactDom", enzymeRoots) : declared("reactDom", roots.slice(Math.max(rtlRoot, 0))) ?? declared("reactDom");
396
423
  // `render` with a container, `rerender`, `unmount`, and `fireEvent` are all there since RTL 10
397
424
  const rtlMajor = added ? ((enzymeReact as DeclaredVersion).major >= 18 ? 16 : 12) : typeof rtl === "object" && rtl.major >= 10 && rtl.major <= 16 ? rtl.major : 0;
398
425
  const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major &&
@@ -401,13 +428,43 @@ function compatibility(packages: Packages, sourcePath: string, landed: ReadonlyS
401
428
  }
402
429
 
403
430
  /**
404
- * Whether an RTL major renders with a React major as the runtime tests show: RTL 10 to 12 with React 16 and 17,
405
- * and RTL 16 with React 18, where RTL 13 to 15 also render but are not covered.
431
+ * The package roots, nearest first, of a workspace member that declares Enzyme and that the workspace's root or
432
+ * another of its members, owning the source, depends on by name, as a workspace's packages do on a shared Jest preset. Its dependencies are
433
+ * hoisted to the workspace's `node_modules`, where the source resolves Enzyme today and RTL once it is added there.
434
+ */
435
+ function providerRoots(packages: Packages, roots: readonly string[]): string[] {
436
+ // A package outside the provider's workspace installs a published package of that name in its own `node_modules`
437
+ const workspace = (root: string) => [...packages.entries()].find(([, declarations]) => declarations.members.has(root))?.[0];
438
+ const provider = [...packages.entries()].find(([path, declarations]) => declarations.enzyme && declarations.name !== undefined &&
439
+ workspace(path) !== undefined && roots.some(root => packages.get(root)!.dependencies.has(declarations.name!) &&
440
+ (root === workspace(path) || workspace(root) === workspace(path))))?.[0];
441
+ if (provider === undefined) return [];
442
+ return [...packages.keys()].filter(root => provider.startsWith(root)).sort((a, b) => b.length - a.length);
443
+ }
444
+
445
+ /**
446
+ * Whether an RTL major renders with a React major as the runtime tests show: RTL 12 with React 15.5+, RTL 10 to 12 with
447
+ * React 16 and 17, and RTL 16 with React 18, where RTL 13 to 15 also render but are not covered.
406
448
  */
407
449
  function rtlSupports(rtl: number, react: number): boolean {
450
+ if (react === 15) return rtl === 12;
408
451
  return react <= 17 ? rtl <= 12 : rtl === 16;
409
452
  }
410
453
 
454
+ // Babel 6 presets and their core, which parse neither `?.` nor `??`
455
+ const BABEL_6 = ["babel-preset-es2015", "babel-preset-es2016", "babel-preset-es2017", "babel-preset-latest", "babel-preset-stage-0", "babel-preset-stage-1"];
456
+
457
+ /**
458
+ * Whether a package's own dependencies parse optional chaining: not with Babel 6, Babel 7 before 7.8 (whose preset-env
459
+ * lacks the proposal), or react-scripts before 3.3, and in TypeScript tests not with TypeScript before 3.7.
460
+ */
461
+ function optionalChainingOf(declares: (name: string) => boolean, version: (name: string) => Declaration): {js: boolean, ts: boolean} {
462
+ const babel6 = !declares("@babel/core") && (BABEL_6.some(declares) || below(version("babel-core"), 7, 0) ||
463
+ below(version("babel-preset-env"), 2, 0) || below(version("babel-cli"), 7, 0));
464
+ const js = !babel6 && !below(version("@babel/core"), 7, 8) && !below(version("react-scripts"), 3, 3);
465
+ return {js, ts: js && !below(version("typescript"), 3, 7)};
466
+ }
467
+
411
468
  /**
412
469
  * A version or a range within a single major: `16.14.0`, `^16.14`, `~16.9.0`, `16.9.x`, or `^17`,
413
470
  * whose minor version is known only where it is a lower bound.
@@ -448,7 +505,7 @@ function declaredVersion(version: string | undefined): Declaration {
448
505
  export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
449
506
  readonly name: string = "org.openrewrite.react.migrate.enzyme-to-react-testing-library";
450
507
  readonly displayName: string = "Migrate Enzyme to React Testing Library";
451
- readonly description: string = "Migrates Enzyme `mount` wrappers whose every use is a supported DOM read or event (`find(selector).length`, `.exists()`, `.text()`, `.html()`, `.hasClass()`, positions through `.at(n)`, `.first()`, `.last()`, the wrapper's `text()` and `exists(selector)`, found nodes as a `toHaveLength` subject, `setProps` as a rerender of the cloned element, and `simulate` with common mouse, keyboard, focus, form, and touch events, including `nativeEvent` mocks, on React 17 and 18 and, without the hover events and in a render attached to the document, on React 16.9+) and bare `mount` statements to React Testing Library container queries, `rerender`, and `fireEvent` in packages using React 16.9+/17 with RTL 10 to 12 or React 18 with RTL 16, adding RTL 12, or RTL 16 with its peer `@testing-library/dom` 10, where it is missing. Converts `shallow` wrappers the same way, without `simulate` or `html()`, where the component is imported from a source in the repository that creates host elements only and runs no effects, so a full render produces the DOM the shallow render does. Selectors are limited to HTML or SVG tag, class, ID, and pass-through attribute compounds and their descendant combinations. Reports remaining Enzyme usages for manual review. Requires an existing DOM test environment; shared wrappers, props, snapshots, and shallow rendering of other components are left for review.";
508
+ 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; shared wrappers, props, snapshots, and shallow rendering of other components are left for review.";
452
509
 
453
510
  @Option({
454
511
  displayName: "Convert positions into untagged selector matches",
@@ -481,7 +538,7 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
481
538
 
482
539
  initialValue(): Scanned {
483
540
  this.tests.length = 0;
484
- return {packages: new Map(), components: new Map(), modules: new Map(), names: new Map()};
541
+ return {packages: new Map(), components: new Map(), modules: new Map(), names: new Map(), nullSnapshots: new Set()};
485
542
  }
486
543
 
487
544
  // The host may prepare the visitors before there is an accumulator, so it is read only while visiting
@@ -522,28 +579,42 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
522
579
  reactDom: declaredVersion(version("react-dom")),
523
580
  rtl: declaredVersion(version(RTL)),
524
581
  enzyme: dependencies.some(dep => dep.name === "enzyme"),
582
+ name: resolution?.name,
583
+ members: new Set((resolution?.workspacePackagePaths ?? []).map(member => member.replace(/^\.\//, "").slice(0, -"package.json".length))),
525
584
  dependencies: new Set(dependencies.map(dep => dep.name)),
526
585
  rootStyles: (resolution?.resolvedDependencies ?? []).some(dep => {
527
586
  const range = ROOT_STYLES.get(dep.name);
528
587
  return range !== undefined && valid(dep.version) !== null && satisfies(dep.version, range);
529
- })
588
+ }),
589
+ optionalChaining: optionalChainingOf(name => dependencies.some(dep => dep.name === name), name => declaredVersion(version(name)))
530
590
  });
531
591
  return doc;
532
592
  }
533
593
  }();
534
594
  const scan = new class extends TreeVisitor<any, ExecutionContext> {
535
595
  override async isAcceptable(sourceFile: SourceFile): Promise<boolean> {
536
- return await manifests.isAcceptable(sourceFile) || await sources.isAcceptable(sourceFile);
596
+ return isPlainText(sourceFile) && SNAPSHOT_FILE.test(sourceFile.sourcePath) || await manifests.isAcceptable(sourceFile) || await sources.isAcceptable(sourceFile);
537
597
  }
538
598
 
539
599
  override async visit<R extends Tree>(tree: Tree, ctx: ExecutionContext, parent?: Cursor): Promise<R | undefined> {
600
+ if (isPlainText(tree)) {
601
+ const snapshot = SNAPSHOT_FILE.exec(tree.sourcePath);
602
+ if (snapshot && NULL_SNAPSHOT.test(tree.text)) scanned.nullSnapshots.add(snapshot[1] + snapshot[2]);
603
+ }
540
604
  if (tree.kind === Json.Kind.Document) return await manifests.visit(tree, ctx, parent) as R | undefined;
541
605
  return tree.kind === JS.Kind.CompilationUnit ? await sources.visit(tree, ctx, parent) as R | undefined : tree as R;
542
606
  }
543
607
  }();
544
608
  // HACK: the host infers which trees to send only from a JsonVisitor or JavaScriptVisitor, and sends a
545
- // plain TreeVisitor every tree, including Python ones the TypeScript side has no codec for
546
- return check(or(treesOfType("org.openrewrite.json.tree.Json"), treesOfType("org.openrewrite.javascript.tree.JS")), scan);
609
+ // plain TreeVisitor every tree, including Python ones the TypeScript side has no codec for; of plain text, only Jest snapshot files
610
+ return check(or(treesOfType("org.openrewrite.json.tree.Json"), treesOfType("org.openrewrite.javascript.tree.JS"),
611
+ and(treesOfType("org.openrewrite.text.PlainText"), new RecipeRef("org.openrewrite.FindSourceFiles", {filePattern: "**/__snapshots__/*.snap"}))), scan);
612
+ }
613
+
614
+ // HACK: core's ScanningRecipe.editor() hides editorWithData behind a lazy wrapper, so PrepareRecipe would send the
615
+ // host no edit gate and the host would send the editor every tree (openrewrite/rewrite#9734)
616
+ override async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
617
+ return check(treesOfType("org.openrewrite.javascript.tree.JS"), super.editor());
547
618
  }
548
619
 
549
620
  async editorWithData(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
@@ -609,6 +680,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
609
680
  private reactMajor = 0;
610
681
  private events: SimulatedEvents = {events: new Set(), attached: false};
611
682
  private rootStyles = false;
683
+ private optionalChaining = true;
684
+ private nullSnapshots = false;
612
685
  private typescript = false;
613
686
  private sourcePath = "";
614
687
  private readonly mounts = new Map<string, ConvertedRender>();
@@ -643,7 +716,9 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
643
716
  this.reactMajor = reactMajor(scanned.packages, cu.sourcePath, landed);
644
717
  this.events = simulatesEvents(scanned.packages, cu.sourcePath, landed);
645
718
  this.rootStyles = injectsRootStyles(scanned.packages, cu.sourcePath);
719
+ this.nullSnapshots = scanned.nullSnapshots.has(cu.sourcePath);
646
720
  this.typescript = isTypeScript(cu);
721
+ this.optionalChaining = parsesOptionalChaining(scanned.packages, cu.sourcePath, this.typescript);
647
722
  this.enabled = this.reactMajor > 0 && moduleBindings(this).moduleSystem === "esm";
648
723
  if (!this.enabled) return cu;
649
724
  this.imports = relativeImports(cu, scanned.components);
@@ -675,7 +750,9 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
675
750
  if (!candidate) continue;
676
751
  const api = candidate.render;
677
752
  const reads = READS[api];
678
- const scope = analyzeWrapperScope(this.cursor, candidate, {events: reads.simulate ? this.events.events : new Set(), html: reads.html, untaggedPositions, hostNames, snapshots,
753
+ // React 15 marks its markup with `data-reactroot` and empty renders with comments, which Enzyme's html() leaves out
754
+ const markup = this.reactMajor >= 16;
755
+ 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,
679
756
  constant: node => this.constantString(node)});
680
757
  if (!scope) continue;
681
758
  if ([...scope.uses.values()].some(use => use.use === "setProps" && !reads.props(use.props!, this.importedNames))) continue;
@@ -871,13 +948,21 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
871
948
  // An element's text content is never null, though its type allows it
872
949
  case "text":
873
950
  return code.param(read.wrapper).code(".container.textContent" + (read.unasserted && this.typescript ? "!" : "")).build();
951
+ // Without optional chaining, a read that throws where nothing is found, as Enzyme's does
874
952
  case "selectorText":
875
- if (read.unasserted) return element(true).code(".textContent" + (this.typescript ? "!" : "")).build();
953
+ if (read.unasserted || !this.optionalChaining) return element(true).code(".textContent" + (this.typescript ? "!" : "")).build();
876
954
  return element(false).code("?.textContent").build();
877
- case "html":
878
- return element(!!read.unasserted).code(read.unasserted ? ".outerHTML" : "?.outerHTML").build();
879
- case "rootHtml":
880
- return code.param(read.wrapper).code(".container.innerHTML").build();
955
+ case "html": {
956
+ const throwing = !!read.unasserted || !this.optionalChaining;
957
+ return element(throwing).code(throwing ? ".outerHTML" : "?.outerHTML").build();
958
+ }
959
+ // Enzyme's html() is null where nothing renders, as a container without child nodes is; only a stored
960
+ // snapshot of that null tells the two apart, so other snapshots keep the plain markup
961
+ case "rootHtml": {
962
+ const nullable = read.snapshot && this.nullSnapshots;
963
+ if (nullable) code.param(read.wrapper).code(".container.childNodes.length ? ");
964
+ return code.param(read.wrapper).code(".container.innerHTML" + (nullable ? " : null" : "")).build();
965
+ }
881
966
  case "node":
882
967
  return element(true).build();
883
968
  case "hasClass":