@openrewrite/recipes-react 0.16.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 (244) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +10 -5
  4. package/dist/index.js.map +1 -1
  5. package/dist/migration/cra-to-vite/add-vite-config.d.ts +7 -0
  6. package/dist/migration/cra-to-vite/add-vite-config.d.ts.map +1 -1
  7. package/dist/migration/cra-to-vite/add-vite-config.js +58 -1
  8. package/dist/migration/cra-to-vite/add-vite-config.js.map +1 -1
  9. package/dist/migration/cra-to-vite/cra-file-gate.d.ts +3 -0
  10. package/dist/migration/cra-to-vite/cra-file-gate.d.ts.map +1 -0
  11. package/dist/migration/cra-to-vite/cra-file-gate.js +10 -0
  12. package/dist/migration/cra-to-vite/cra-file-gate.js.map +1 -0
  13. package/dist/migration/cra-to-vite/cra-runtime.d.ts +2 -0
  14. package/dist/migration/cra-to-vite/cra-runtime.d.ts.map +1 -0
  15. package/dist/migration/cra-to-vite/cra-runtime.js +24 -0
  16. package/dist/migration/cra-to-vite/cra-runtime.js.map +1 -0
  17. package/dist/migration/cra-to-vite/cra-script.d.ts +8 -0
  18. package/dist/migration/cra-to-vite/cra-script.d.ts.map +1 -0
  19. package/dist/migration/cra-to-vite/cra-script.js +82 -0
  20. package/dist/migration/cra-to-vite/cra-script.js.map +1 -0
  21. package/dist/migration/cra-to-vite/cra-to-vite.d.ts +2 -1
  22. package/dist/migration/cra-to-vite/cra-to-vite.d.ts.map +1 -1
  23. package/dist/migration/cra-to-vite/cra-to-vite.js +23 -16
  24. package/dist/migration/cra-to-vite/cra-to-vite.js.map +1 -1
  25. package/dist/migration/cra-to-vite/cra-typecheck.d.ts +4 -0
  26. package/dist/migration/cra-to-vite/cra-typecheck.d.ts.map +1 -0
  27. package/dist/migration/cra-to-vite/cra-typecheck.js +35 -0
  28. package/dist/migration/cra-to-vite/cra-typecheck.js.map +1 -0
  29. package/dist/migration/cra-to-vite/find-cra-config-blockers.d.ts.map +1 -1
  30. package/dist/migration/cra-to-vite/find-cra-config-blockers.js +5 -6
  31. package/dist/migration/cra-to-vite/find-cra-config-blockers.js.map +1 -1
  32. package/dist/migration/cra-to-vite/index.d.ts +8 -2
  33. package/dist/migration/cra-to-vite/index.d.ts.map +1 -1
  34. package/dist/migration/cra-to-vite/index.js +17 -2
  35. package/dist/migration/cra-to-vite/index.js.map +1 -1
  36. package/dist/migration/cra-to-vite/migrate-cra-package.d.ts +17 -0
  37. package/dist/migration/cra-to-vite/migrate-cra-package.d.ts.map +1 -0
  38. package/dist/migration/cra-to-vite/migrate-cra-package.js +181 -0
  39. package/dist/migration/cra-to-vite/migrate-cra-package.js.map +1 -0
  40. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts +9 -0
  41. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.d.ts.map +1 -0
  42. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js +66 -0
  43. package/dist/migration/cra-to-vite/migrate-cra-svg-imports.js.map +1 -0
  44. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts +49 -0
  45. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.d.ts.map +1 -0
  46. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js +506 -0
  47. package/dist/migration/cra-to-vite/migrate-cra-tests-to-vitest.js.map +1 -0
  48. package/dist/migration/cra-to-vite/move-public-index-html.d.ts +2 -0
  49. package/dist/migration/cra-to-vite/move-public-index-html.d.ts.map +1 -1
  50. package/dist/migration/cra-to-vite/move-public-index-html.js +12 -7
  51. package/dist/migration/cra-to-vite/move-public-index-html.js.map +1 -1
  52. package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts +30 -0
  53. package/dist/migration/cra-to-vite/plan-cra-to-vite.d.ts.map +1 -0
  54. package/dist/migration/cra-to-vite/plan-cra-to-vite.js +428 -0
  55. package/dist/migration/cra-to-vite/plan-cra-to-vite.js.map +1 -0
  56. package/dist/migration/cra-to-vite/prepare-cra-package.d.ts +15 -0
  57. package/dist/migration/cra-to-vite/prepare-cra-package.d.ts.map +1 -0
  58. package/dist/migration/cra-to-vite/prepare-cra-package.js +100 -0
  59. package/dist/migration/cra-to-vite/prepare-cra-package.js.map +1 -0
  60. package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts +12 -0
  61. package/dist/migration/cra-to-vite/remove-cra-configuration.d.ts.map +1 -0
  62. package/dist/migration/cra-to-vite/remove-cra-configuration.js +85 -0
  63. package/dist/migration/cra-to-vite/remove-cra-configuration.js.map +1 -0
  64. package/dist/migration/cra-to-vite/rename-jsx-files.d.ts +20 -0
  65. package/dist/migration/cra-to-vite/rename-jsx-files.d.ts.map +1 -0
  66. package/dist/migration/cra-to-vite/rename-jsx-files.js +220 -0
  67. package/dist/migration/cra-to-vite/rename-jsx-files.js.map +1 -0
  68. package/dist/migration/cra-to-vite/rename-process-env-react-app.d.ts.map +1 -1
  69. package/dist/migration/cra-to-vite/rename-process-env-react-app.js +6 -3
  70. package/dist/migration/cra-to-vite/rename-process-env-react-app.js.map +1 -1
  71. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js +1 -1
  72. package/dist/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.js.map +1 -1
  73. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts +11 -4
  74. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.d.ts.map +1 -1
  75. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js +47 -30
  76. package/dist/migration/cra-to-vite/replace-react-scripts-dependency.js.map +1 -1
  77. package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts +3 -0
  78. package/dist/migration/cra-to-vite/resolved-cra-dependency.d.ts.map +1 -0
  79. package/dist/migration/cra-to-vite/resolved-cra-dependency.js +42 -0
  80. package/dist/migration/cra-to-vite/resolved-cra-dependency.js.map +1 -0
  81. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts +13 -0
  82. package/dist/migration/cra-to-vite/scan-cra-projects.d.ts.map +1 -1
  83. package/dist/migration/cra-to-vite/scan-cra-projects.js +52 -4
  84. package/dist/migration/cra-to-vite/scan-cra-projects.js.map +1 -1
  85. package/dist/migration/cra-to-vite/shared.d.ts +1 -1
  86. package/dist/migration/cra-to-vite/shared.d.ts.map +1 -1
  87. package/dist/migration/cra-to-vite/shared.js +19 -4
  88. package/dist/migration/cra-to-vite/shared.js.map +1 -1
  89. package/dist/migration/cra-to-vite/svg-component.d.ts +5 -0
  90. package/dist/migration/cra-to-vite/svg-component.d.ts.map +1 -0
  91. package/dist/migration/cra-to-vite/svg-component.js +60 -0
  92. package/dist/migration/cra-to-vite/svg-component.js.map +1 -0
  93. package/dist/migration/cra-to-vite/update-react-app-env-types.d.ts.map +1 -1
  94. package/dist/migration/cra-to-vite/update-react-app-env-types.js +12 -3
  95. package/dist/migration/cra-to-vite/update-react-app-env-types.js.map +1 -1
  96. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts +3 -2
  97. package/dist/migration/cra-to-vite/update-react-scripts-scripts.d.ts.map +1 -1
  98. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js +18 -14
  99. package/dist/migration/cra-to-vite/update-react-scripts-scripts.js.map +1 -1
  100. package/dist/react18/replace-reactdom-render.d.ts.map +1 -1
  101. package/dist/react18/replace-reactdom-render.js +16 -8
  102. package/dist/react18/replace-reactdom-render.js.map +1 -1
  103. package/dist/react18/replace-unmount-component-at-node.d.ts.map +1 -1
  104. package/dist/react18/replace-unmount-component-at-node.js +8 -1
  105. package/dist/react18/replace-unmount-component-at-node.js.map +1 -1
  106. package/dist/react19/find-legacy-context-api.d.ts.map +1 -1
  107. package/dist/react19/find-legacy-context-api.js +21 -38
  108. package/dist/react19/find-legacy-context-api.js.map +1 -1
  109. package/dist/{react18 → react19}/remove-unstable-batched-updates.d.ts +2 -2
  110. package/dist/react19/remove-unstable-batched-updates.d.ts.map +1 -0
  111. package/dist/react19/remove-unstable-batched-updates.js +295 -0
  112. package/dist/react19/remove-unstable-batched-updates.js.map +1 -0
  113. package/dist/react19/replace-default-props.d.ts +1 -0
  114. package/dist/react19/replace-default-props.d.ts.map +1 -1
  115. package/dist/react19/replace-default-props.js +198 -151
  116. package/dist/react19/replace-default-props.js.map +1 -1
  117. package/dist/react19/replace-react-shallow-renderer.d.ts.map +1 -1
  118. package/dist/react19/replace-react-shallow-renderer.js +10 -25
  119. package/dist/react19/replace-react-shallow-renderer.js.map +1 -1
  120. package/dist/refactoring/class-to-functional.d.ts.map +1 -1
  121. package/dist/refactoring/class-to-functional.js +2 -0
  122. package/dist/refactoring/class-to-functional.js.map +1 -1
  123. package/dist/refactoring/create-class-to-es6.d.ts.map +1 -1
  124. package/dist/refactoring/create-class-to-es6.js +14 -49
  125. package/dist/refactoring/create-class-to-es6.js.map +1 -1
  126. package/dist/search/find-function-component-default-props.d.ts.map +1 -1
  127. package/dist/search/find-function-component-default-props.js +6 -15
  128. package/dist/search/find-function-component-default-props.js.map +1 -1
  129. package/dist/search/find-redux-stores.d.ts +12 -0
  130. package/dist/search/find-redux-stores.d.ts.map +1 -0
  131. package/dist/search/find-redux-stores.js +87 -0
  132. package/dist/search/find-redux-stores.js.map +1 -0
  133. package/dist/simplify-object-pattern-property.d.ts.map +1 -1
  134. package/dist/simplify-object-pattern-property.js +14 -21
  135. package/dist/simplify-object-pattern-property.js.map +1 -1
  136. package/dist/simplify-react-imports.d.ts.map +1 -1
  137. package/dist/simplify-react-imports.js +10 -59
  138. package/dist/simplify-react-imports.js.map +1 -1
  139. package/dist/testing/enzyme-constant-strings.d.ts +12 -0
  140. package/dist/testing/enzyme-constant-strings.d.ts.map +1 -0
  141. package/dist/testing/enzyme-constant-strings.js +101 -0
  142. package/dist/testing/enzyme-constant-strings.js.map +1 -0
  143. package/dist/testing/enzyme-host-components.d.ts.map +1 -1
  144. package/dist/testing/enzyme-host-components.js +5 -2
  145. package/dist/testing/enzyme-host-components.js.map +1 -1
  146. package/dist/testing/enzyme-portals.d.ts +38 -0
  147. package/dist/testing/enzyme-portals.d.ts.map +1 -0
  148. package/dist/testing/enzyme-portals.js +226 -0
  149. package/dist/testing/enzyme-portals.js.map +1 -0
  150. package/dist/testing/enzyme-selector-names.d.ts +9 -0
  151. package/dist/testing/enzyme-selector-names.d.ts.map +1 -0
  152. package/dist/testing/enzyme-selector-names.js +50 -0
  153. package/dist/testing/enzyme-selector-names.js.map +1 -0
  154. package/dist/testing/enzyme-to-react-testing-library.d.ts +80 -8
  155. package/dist/testing/enzyme-to-react-testing-library.d.ts.map +1 -1
  156. package/dist/testing/enzyme-to-react-testing-library.js +384 -40
  157. package/dist/testing/enzyme-to-react-testing-library.js.map +1 -1
  158. package/dist/testing/enzyme-usage.d.ts.map +1 -1
  159. package/dist/testing/enzyme-usage.js +27 -4
  160. package/dist/testing/enzyme-usage.js.map +1 -1
  161. package/dist/testing/enzyme-wrapper-scope.d.ts +14 -6
  162. package/dist/testing/enzyme-wrapper-scope.d.ts.map +1 -1
  163. package/dist/testing/enzyme-wrapper-scope.js +143 -16
  164. package/dist/testing/enzyme-wrapper-scope.js.map +1 -1
  165. package/dist/util/java-recipe-proxy.d.ts +18 -0
  166. package/dist/util/java-recipe-proxy.d.ts.map +1 -0
  167. package/dist/util/java-recipe-proxy.js +97 -0
  168. package/dist/util/java-recipe-proxy.js.map +1 -0
  169. package/dist/util/module-imports.d.ts +1 -0
  170. package/dist/util/module-imports.d.ts.map +1 -1
  171. package/dist/util/module-imports.js +5 -1
  172. package/dist/util/module-imports.js.map +1 -1
  173. package/dist/util/reindent.d.ts +5 -0
  174. package/dist/util/reindent.d.ts.map +1 -0
  175. package/dist/util/reindent.js +44 -0
  176. package/dist/util/reindent.js.map +1 -0
  177. package/dist/zustand/redux-stores.d.ts +74 -0
  178. package/dist/zustand/redux-stores.d.ts.map +1 -0
  179. package/dist/zustand/redux-stores.js +402 -0
  180. package/dist/zustand/redux-stores.js.map +1 -0
  181. package/dist/zustand/redux-to-zustand.d.ts +76 -0
  182. package/dist/zustand/redux-to-zustand.d.ts.map +1 -0
  183. package/dist/zustand/redux-to-zustand.js +653 -0
  184. package/dist/zustand/redux-to-zustand.js.map +1 -0
  185. package/dist/zustand/zustand-plan.d.ts +96 -0
  186. package/dist/zustand/zustand-plan.d.ts.map +1 -0
  187. package/dist/zustand/zustand-plan.js +822 -0
  188. package/dist/zustand/zustand-plan.js.map +1 -0
  189. package/package.json +2 -2
  190. package/src/index.ts +9 -4
  191. package/src/migration/cra-to-vite/add-vite-config.ts +53 -1
  192. package/src/migration/cra-to-vite/cra-file-gate.ts +8 -0
  193. package/src/migration/cra-to-vite/cra-runtime.ts +16 -0
  194. package/src/migration/cra-to-vite/cra-script.ts +61 -0
  195. package/src/migration/cra-to-vite/cra-to-vite.ts +25 -36
  196. package/src/migration/cra-to-vite/cra-typecheck.ts +33 -0
  197. package/src/migration/cra-to-vite/find-cra-config-blockers.ts +5 -6
  198. package/src/migration/cra-to-vite/index.ts +10 -2
  199. package/src/migration/cra-to-vite/migrate-cra-package.ts +127 -0
  200. package/src/migration/cra-to-vite/migrate-cra-svg-imports.ts +41 -0
  201. package/src/migration/cra-to-vite/migrate-cra-tests-to-vitest.ts +376 -0
  202. package/src/migration/cra-to-vite/move-public-index-html.ts +12 -7
  203. package/src/migration/cra-to-vite/plan-cra-to-vite.ts +283 -0
  204. package/src/migration/cra-to-vite/prepare-cra-package.ts +86 -0
  205. package/src/migration/cra-to-vite/remove-cra-configuration.ts +64 -0
  206. package/src/migration/cra-to-vite/rename-jsx-files.ts +155 -0
  207. package/src/migration/cra-to-vite/rename-process-env-react-app.ts +6 -3
  208. package/src/migration/cra-to-vite/rename-react-app-env-vars-in-env-files.ts +1 -1
  209. package/src/migration/cra-to-vite/replace-react-scripts-dependency.ts +52 -33
  210. package/src/migration/cra-to-vite/resolved-cra-dependency.ts +41 -0
  211. package/src/migration/cra-to-vite/scan-cra-projects.ts +57 -6
  212. package/src/migration/cra-to-vite/shared.ts +20 -10
  213. package/src/migration/cra-to-vite/svg-component.ts +39 -0
  214. package/src/migration/cra-to-vite/update-react-app-env-types.ts +13 -6
  215. package/src/migration/cra-to-vite/update-react-scripts-scripts.ts +22 -28
  216. package/src/react18/replace-reactdom-render.ts +17 -8
  217. package/src/react18/replace-unmount-component-at-node.ts +13 -2
  218. package/src/react19/find-legacy-context-api.ts +21 -42
  219. package/src/react19/remove-unstable-batched-updates.ts +301 -0
  220. package/src/react19/replace-default-props.ts +212 -159
  221. package/src/react19/replace-react-shallow-renderer.ts +13 -36
  222. package/src/refactoring/class-to-functional.ts +3 -1
  223. package/src/refactoring/create-class-to-es6.ts +12 -63
  224. package/src/search/find-function-component-default-props.ts +8 -10
  225. package/src/search/find-redux-stores.ts +76 -0
  226. package/src/simplify-object-pattern-property.ts +22 -49
  227. package/src/simplify-react-imports.ts +12 -66
  228. package/src/testing/enzyme-constant-strings.ts +95 -0
  229. package/src/testing/enzyme-host-components.ts +6 -2
  230. package/src/testing/enzyme-portals.ts +279 -0
  231. package/src/testing/enzyme-selector-names.ts +59 -0
  232. package/src/testing/enzyme-to-react-testing-library.ts +517 -57
  233. package/src/testing/enzyme-usage.ts +29 -4
  234. package/src/testing/enzyme-wrapper-scope.ts +186 -30
  235. package/src/util/java-recipe-proxy.ts +94 -0
  236. package/src/util/module-imports.ts +6 -1
  237. package/src/util/reindent.ts +35 -0
  238. package/src/zustand/redux-stores.ts +409 -0
  239. package/src/zustand/redux-to-zustand.ts +657 -0
  240. package/src/zustand/zustand-plan.ts +843 -0
  241. package/dist/react18/remove-unstable-batched-updates.d.ts.map +0 -1
  242. package/dist/react18/remove-unstable-batched-updates.js +0 -170
  243. package/dist/react18/remove-unstable-batched-updates.js.map +0 -1
  244. package/src/react18/remove-unstable-batched-updates.ts +0 -192
@@ -1,26 +1,204 @@
1
- import {and, check, Cursor, DataTable, ExecutionContext, findMarker, not, Option, or, ScanningRecipe, Tree, TreePrinters, TreeVisitor} from "@openrewrite/rewrite";
2
- import {addDependency, AddDependencyOptions, autoFormat, capture, PrettierStyle, deconflict, findNodeResolutionResult, isTypeScript, isVendoredOrBundled, JavaScriptVisitor, JS, maybeRemoveImport, moduleBindings, namesUsedIn, pattern, raw, rewrite, scopeOf, StyleKind, Template, template, usesMethod} from "@openrewrite/rewrite/javascript";
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";
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";
5
6
  import {Json, JsonVisitor} from "@openrewrite/rewrite/json";
6
7
  import {readFileSync} from "fs";
7
8
  import {dirname, join} from "path";
8
- import {satisfies, validRange} from "semver";
9
+ import {satisfies, valid, validRange} from "semver";
9
10
  import {FindEnzymeUsage} from "../search/find-enzyme-usage";
11
+ import {JavaDependencyRecipe, treesOfType} from "../util/java-recipe-proxy";
12
+ import {importBindings} from "../util/module-imports";
10
13
  import {ENZYME, ENZYME_USAGE_TABLE, enclosingScope, enzymeMethod, EnzymeUsageRow} from "./enzyme-usage";
11
14
  import {HostComponents, hostComponentExports, ImportedExport, importedNames, propsRenderHostElements, relativeImports, rendersHostElements} from "./enzyme-host-components";
12
- import {analyzeWrapperScope, idsWithin, innermostCall, mountedElement, selectorLiteral, simpleChain, statementPosition, variableCursor, withoutEnzymeTypes, withRenderOptionsOnElementLine, wrapperDeclaration, WrapperRead} from "./enzyme-wrapper-scope";
15
+ import {moduleFacts, Modules, rendersPortal, resolver} from "./enzyme-portals";
16
+ import {evaluate, stringParts} from "./enzyme-constant-strings";
17
+ import {hostOnlyNames, selectorNames, SelectorNames} from "./enzyme-selector-names";
18
+ import {analyzeWrapperScope, SIMULATED_EVENTS, idsWithin, innermostCall, mountedElement, passesRef, selectorLiteral, simpleChain, statementPosition, variableCursor, withoutEnzymeTypes, withRenderOptionsOnElementLine, wrapperDeclaration, WrapperRead, WrapperUse} from "./enzyme-wrapper-scope";
13
19
 
14
20
  const RTL = "@testing-library/react";
15
21
 
16
- const REACT_RANGE = ">=16.9.0 <18";
22
+ const REACT_RANGE = ">=15.5.0 <18";
17
23
 
18
- /** RTL 12 supports React 16.9 to 17, so it goes where Enzyme is used with those. */
24
+ const REACT_18_RANGE = ">=18.0.0 <19";
25
+
26
+ const resolvingReact = (range: string) => [`react@${range}`, `react-dom@${range}`];
27
+
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. */
19
29
  const RTL_ADDITION: AddDependencyOptions = {
20
30
  packageName: RTL, version: "^12.1.5", scope: "devDependencies",
21
- onlyIfDeclaring: ["enzyme"], onlyIfResolving: [`react@${REACT_RANGE}`, `react-dom@${REACT_RANGE}`]
31
+ onlyIfDeclaring: ["enzyme"], onlyIfResolving: resolvingReact(REACT_RANGE)
22
32
  };
23
33
 
34
+ /** RTL 16 supports React 18 with `@testing-library/dom` 10 as a peer, which a package must declare itself. */
35
+ const RTL_18_ADDITION: AddDependencyOptions = {...RTL_ADDITION, version: "^16.3.0", onlyIfResolving: resolvingReact(REACT_18_RANGE)};
36
+
37
+ const DOM = "@testing-library/dom";
38
+ const DOM_18_ADDITION: AddDependencyOptions = {...RTL_18_ADDITION, packageName: DOM, version: "^10.4.0"};
39
+
40
+ /**
41
+ * The test sources the converter would convert were RTL added to every package that may take it, which the
42
+ * dependency steps read so that they add RTL only where a source converts. The converter sets it while it
43
+ * scans. Mutated in place, as copies of a prepared recipe share it.
44
+ */
45
+ export interface ConversionForecast {
46
+ converting?: () => Promise<ReadonlySet<string>>;
47
+ }
48
+
49
+ /** The directory of a `package.json`, such as `packages/ui/`, or `""` at the repository's root. */
50
+ function packageRoot(manifestPath: string): string {
51
+ return manifestPath.slice(0, -"package.json".length);
52
+ }
53
+
54
+ /**
55
+ * Each manifest's lockfile scope: the root of the workspace it is a member of, or its own root. A package manager
56
+ * installs a workspace's members together, and `AddDependency` declines the edit for every member when one is
57
+ * kept from it, so a workspace takes RTL as a whole or not at all.
58
+ */
59
+ export function lockfileScopes(manifests: readonly Json.Document[]): Map<string, string> {
60
+ const scopes = new Map<string, string>();
61
+ for (const manifest of manifests) {
62
+ const root = packageRoot(manifest.sourcePath);
63
+ if (!scopes.has(manifest.sourcePath)) scopes.set(manifest.sourcePath, root);
64
+ // NOTE: the parser lists members from the same base as `sourcePath`, the repository's root, not the workspace's
65
+ for (const member of findNodeResolutionResult(manifest)?.workspacePackagePaths ?? []) {
66
+ scopes.set(member.replace(/^\.\//, ""), root);
67
+ }
68
+ }
69
+ return scopes;
70
+ }
71
+
72
+ /** Adds a test dependency where Enzyme tests are migrated, with its gates, as Java's `AddDependency` does. */
73
+ abstract class EnzymeTestDependency extends JavaDependencyRecipe {
74
+ /**
75
+ * The package roots, such as `packages/ui/`, whose `package.json` declares the dependency once this run's
76
+ * edit lands, known from the end of `generate` on. Mutated in place, as copies of a prepared recipe share it.
77
+ */
78
+ readonly landed = new Set<string>();
79
+
80
+ private readonly manifests: Json.Document[] = [];
81
+
82
+ /** The manifests the step admits, which reach the Java recipe only in `generate`, once the forecast is known. */
83
+ private readonly held: Json.Document[] = [];
84
+
85
+ protected constructor(private readonly addition: AddDependencyOptions, private readonly forecast: ConversionForecast) {
86
+ super("org.openrewrite.javascript.AddDependency", addition);
87
+ }
88
+
89
+ override initialValue(): number {
90
+ this.landed.clear();
91
+ this.manifests.length = 0;
92
+ this.held.length = 0;
93
+ return super.initialValue();
94
+ }
95
+
96
+ /** The package roots that would take the dependency, such as `packages/ui/`, known once the scan is done. */
97
+ candidates(): Set<string> {
98
+ return new Set(this.manifests.map(manifest => packageRoot(manifest.sourcePath)));
99
+ }
100
+
101
+ // PERF: only manifests the edit's gate admits are visited again, one RPC round trip each; a monorepo
102
+ // such as next.js holds thousands of fixture manifests
103
+ protected override scanned(manifest: SourceFile): boolean {
104
+ if (manifest.kind !== Json.Kind.Document || !/(^|\/)package\.json$/.test(manifest.sourcePath)) return true;
105
+ if (!this.admits(manifest as Json.Document)) return false;
106
+ if (this.addition.onlyIfDeclaring!.some(name => declares(manifest as Json.Document, name))) this.manifests.push(manifest as Json.Document);
107
+ this.held.push(manifest as Json.Document);
108
+ return false;
109
+ }
110
+
111
+ /** Whether the dependency may go into this `package.json`, beyond the gates `AddDependency` applies itself. */
112
+ protected admits(_manifest: Json.Document): boolean {
113
+ return true;
114
+ }
115
+
116
+ // NOTE: `AddDependency` decides each edit and regenerates the lockfile while it generates, declining a
117
+ // package whose package manager rejects the edit, such as an npm peer conflict. Its editor then returns
118
+ // that decision for a manifest, and the same one again when the run visits it.
119
+ override async generate(acc: number, ctx: ExecutionContext): Promise<SourceFile[]> {
120
+ // Without a forecast, as when the step runs alone, every admitted manifest goes on as before
121
+ const converting = await this.forecast.converting?.();
122
+ const scopes = lockfileScopes(this.held);
123
+ const forwarded = new Set(this.held.filter(manifest => {
124
+ const scope = scopes.get(manifest.sourcePath) ?? packageRoot(manifest.sourcePath);
125
+ return !converting || [...converting].some(source => source.startsWith(scope));
126
+ }));
127
+ const scanner = await this.java.scanner(acc);
128
+ for (const manifest of forwarded) await scanner.visit(manifest, ctx);
129
+ const kept = this.manifests.filter(manifest => forwarded.has(manifest));
130
+ this.manifests.length = 0;
131
+ this.manifests.push(...kept);
132
+ const generated = await super.generate(acc, ctx);
133
+ const editor = await this.java.editorWithData(acc);
134
+ for (const manifest of this.manifests) {
135
+ const edited = await editor.visit<Json.Document>(manifest, ctx);
136
+ if (edited && edited !== manifest && declares(edited, this.addition.packageName)) this.landed.add(manifest.sourcePath.slice(0, -"package.json".length));
137
+ }
138
+ return generated;
139
+ }
140
+ }
141
+
142
+ /** Adds {@link RTL_ADDITION}. */
143
+ export class AddTestingLibraryReact extends EnzymeTestDependency {
144
+ readonly name = "org.openrewrite.react.migrate.add-testing-library-react";
145
+ readonly displayName = "Add `@testing-library/react` where Enzyme tests are migrated";
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.";
147
+
148
+ constructor(forecast: ConversionForecast = {}) {
149
+ super(RTL_ADDITION, forecast);
150
+ }
151
+ }
152
+
153
+ /** Adds {@link RTL_18_ADDITION}. */
154
+ export class AddTestingLibraryReact18 extends EnzymeTestDependency {
155
+ readonly name = "org.openrewrite.react.migrate.add-testing-library-react-18";
156
+ readonly displayName = "Add `@testing-library/react` 16 where Enzyme tests on React 18 are migrated";
157
+ readonly description = "Adds `@testing-library/react` 16 as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 18.";
158
+
159
+ constructor(forecast: ConversionForecast = {}) {
160
+ super(RTL_18_ADDITION, forecast);
161
+ }
162
+ }
163
+
164
+ /** Adds {@link DOM_18_ADDITION}, the peer of {@link RTL_18_ADDITION}. */
165
+ export class AddTestingLibraryDom18 extends EnzymeTestDependency {
166
+ readonly name = "org.openrewrite.react.migrate.add-testing-library-dom-18";
167
+ readonly displayName = "Add `@testing-library/dom` where Enzyme tests on React 18 are migrated";
168
+ readonly description = "Adds `@testing-library/dom` 10, the peer of `@testing-library/react` 16, as a dev dependency to packages that declare `enzyme` and resolve React and React DOM 18.";
169
+
170
+ constructor(forecast: ConversionForecast = {}) {
171
+ super(DOM_18_ADDITION, forecast);
172
+ }
173
+
174
+ // NOTE: an RTL other than 16 depends on its own `@testing-library/dom`, and the converter leaves its package alone.
175
+ // Only a manifest the step would edit is kept from the Java recipe, which regenerates a workspace's lockfile from
176
+ // every member it scanned: one keeping a member back declines the edit for its siblings too.
177
+ protected override admits(manifest: Json.Document): boolean {
178
+ const rtl = declaration(manifest, RTL);
179
+ if (rtl === undefined || !declares(manifest, ENZYME) || declares(manifest, DOM)) return true;
180
+ const resolved = rtl.resolved?.version.match(/^(\d+)\./)?.[1];
181
+ if (resolved !== undefined) return Number(resolved) === 16;
182
+ const version = declaredVersion(rtl.versionConstraint);
183
+ return version !== undefined && version !== "unsupported" && version.major === 16;
184
+ }
185
+ }
186
+
187
+ /** The package roots where the run added an RTL: RTL 12, or RTL 16 where its peer `@testing-library/dom` landed too. */
188
+ export function rtlLanded(rtl: ReadonlySet<string>, rtl18: ReadonlySet<string>, dom18: ReadonlySet<string>): ReadonlySet<string> {
189
+ return new Set([...rtl, ...[...rtl18].filter(root => dom18.has(root))]);
190
+ }
191
+
192
+ function declaration(manifest: Json.Document, name: string) {
193
+ const resolution = findNodeResolutionResult(manifest);
194
+ return [...resolution?.dependencies ?? [], ...resolution?.devDependencies ?? [],
195
+ ...resolution?.optionalDependencies ?? [], ...resolution?.peerDependencies ?? []].find(dep => dep.name === name);
196
+ }
197
+
198
+ function declares(manifest: Json.Document, name: string): boolean {
199
+ return declaration(manifest, name) !== undefined;
200
+ }
201
+
24
202
  /**
25
203
  * Older hosts drop the `onlyIfResolving` option they do not know, which would add RTL to every
26
204
  * package declaring Enzyme, so RTL is only added where the host has it.
@@ -67,6 +245,20 @@ function documentAt(cursor: Cursor): DocumentReference | undefined {
67
245
  return scope.declares("globalThis", "value") ? undefined : "globalThis.document";
68
246
  }
69
247
 
248
+ /**
249
+ * Whether a source is laid out as its Prettier config would lay it out, judged by its indentation. A
250
+ * package can declare a config, such as for its styles, while another formatter, such as ESLint, lays out
251
+ * its tests, and converted statements then keep that layout instead of Prettier's.
252
+ */
253
+ async function formattedBy(cu: JS.CompilationUnit, style: PrettierStyle): Promise<boolean> {
254
+ const detector = Autodetect.detector();
255
+ await detector.sampleJavaScript(cu);
256
+ const detected = detector.getTabsAndIndentsStyle();
257
+ const useTabs = style.config.useTabs === true;
258
+ const tabWidth = typeof style.config.tabWidth === "number" ? style.config.tabWidth : 2;
259
+ return detected.useTabCharacter === useTabs && (useTabs || detected.indentSize === tabWidth);
260
+ }
261
+
70
262
  function renderOptions(document: DocumentReference): string {
71
263
  return `{container: ${document}.createElement('div')}`;
72
264
  }
@@ -92,19 +284,66 @@ interface PackageDeclarations {
92
284
  reactDom: Declaration;
93
285
  rtl: Declaration;
94
286
  enzyme: boolean;
95
- /**
96
- * `addDependency` leaves a package unchanged when it cannot regenerate its lockfile, as for pnpm
97
- * versions it does not reproduce, so only npm and Yarn packages are counted on to receive RTL.
98
- */
99
- lockfileRegenerated: 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>;
291
+ /** The names of every package it depends on, in any dependency section. */
292
+ dependencies: ReadonlySet<string>;
293
+ /** Whether its lockfile resolves a package that puts styles into the root node of a render's container. */
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};
297
+ }
298
+
299
+ /**
300
+ * Packages whose components insert a `<style>` into the root node of the element they render, by the versions that
301
+ * do. In a detached container that root is the container itself, so its `textContent` and `innerHTML` show the
302
+ * style, while Enzyme's `text()` and `html()` read only the nodes React rendered. `@ant-design/icons` does from
303
+ * 5.1.1, for shadow DOM support, and antd 5 bundles it.
304
+ */
305
+ const ROOT_STYLES: ReadonlyMap<string, string> = new Map([["@ant-design/icons", ">=5.1.1"]]);
306
+
307
+ /** Whether the tests of a source file render components that insert styles into a detached container, as {@link ROOT_STYLES} lists. */
308
+ export function injectsRootStyles(packages: Packages, sourcePath: string): boolean {
309
+ return [...packages.entries()].some(([root, declarations]) => sourcePath.startsWith(root) && declarations.rootStyles);
310
+ }
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));
100
316
  }
101
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
+
322
+ /** The reads of a whole container, which see what a component inserts into it besides what React renders. */
323
+ const CONTAINER_READS: ReadonlySet<WrapperUse> = new Set<WrapperUse>(["text", "rootHtml", "snapshot"]);
324
+
102
325
  /** Package roots, such as `packages/ui/`, mapped to their declarations. */
103
326
  type Packages = Map<string, PackageDeclarations>;
104
327
 
105
328
  interface Scanned {
106
329
  packages: Packages;
107
330
  components: HostComponents;
331
+ modules: Modules;
332
+ /** The words of each source's strings, for the selectors whose ancestor compounds name no tag. */
333
+ names: Map<string, SelectorNames>;
334
+ /** The tests whose stored Jest snapshots include Enzyme's `null` for an empty render. */
335
+ nullSnapshots: Set<string>;
336
+ }
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
+
343
+ /** A dry run of the editor: the package roots it takes RTL to have, and the sources it converts. */
344
+ interface DryRun {
345
+ landed: ReadonlySet<string>;
346
+ converted: Set<string>;
108
347
  }
109
348
 
110
349
  /** The Enzyme render a converted wrapper comes from. */
@@ -114,6 +353,8 @@ type Render = "mount" | "shallow";
114
353
  interface ConvertedRender {
115
354
  document: DocumentReference;
116
355
  api: Render;
356
+ /** Whether RTL renders into its default container, attached to the document, for React 16 to receive dispatched events. */
357
+ attached: boolean;
117
358
  }
118
359
 
119
360
  /**
@@ -129,44 +370,101 @@ const READS: Record<Render, {simulate: boolean, html: boolean, props: (props: Ex
129
370
  /**
130
371
  * The React major version the tests of a source file run with, or 0 where they cannot migrate. A
131
372
  * dependency the owning package does not declare comes from the nearest enclosing package that
132
- * does, where Node resolves it from. Where the run adds RTL, as {@link RTL_ADDITION} does, it is
133
- * there for every package within the nearest package declaring Enzyme.
373
+ * does, where Node resolves it from. Where the run added RTL to the nearest package declaring
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.
134
376
  */
135
- export function reactMajor(packages: Packages, sourcePath: string, addsRtl = false): number {
136
- return compatibility(packages, sourcePath, addsRtl).react;
377
+ export function reactMajor(packages: Packages, sourcePath: string, landed: ReadonlySet<string> = new Set()): number {
378
+ return compatibility(packages, sourcePath, landed).react;
379
+ }
380
+
381
+ /** The events `simulate` can dispatch as `fireEvent` in a source file, and whether its render must be attached to the document for them. */
382
+ export interface SimulatedEvents {
383
+ events: ReadonlySet<string>;
384
+ attached: boolean;
137
385
  }
138
386
 
387
+ // React 16 makes `onMouseEnter` and `onMouseLeave` of `mouseover` and `mouseout`, so a dispatched hover event
388
+ // runs the handlers of its pair as well, which `simulate` does not
389
+ const HOVER_EVENTS = new Set(["mouseEnter", "mouseLeave", "mouseOver", "mouseOut"]);
390
+
139
391
  /**
140
- * Whether `simulate` can become `fireEvent` for a source file: on React 17, with an RTL whose
141
- * `fireEvent.focus`, `blur`, `mouseEnter`, and `mouseLeave` also dispatch the events React 17
142
- * listens to, which RTL 10 does only from 10.4.9.
392
+ * Which `simulate` calls can become `fireEvent` for a source file. On React 17, every supported event,
393
+ * with an RTL whose `fireEvent.focus`, `blur`, `mouseEnter`, and `mouseLeave` also dispatch the events React 17
394
+ * listens to, which RTL 10 does only from 10.4.9. On React 15 and 16, which listen on the document rather than
395
+ * the root, every one but the hover events, in a render attached to the document.
143
396
  */
144
- export function simulatesEvents(packages: Packages, sourcePath: string, addsRtl = false): boolean {
145
- const {react, rtl} = compatibility(packages, sourcePath, addsRtl);
146
- return react === 17 && rtl >= 11;
397
+ export function simulatesEvents(packages: Packages, sourcePath: string, landed: ReadonlySet<string> = new Set()): SimulatedEvents {
398
+ const {react, rtl} = compatibility(packages, sourcePath, landed);
399
+ // React 18 listens on the root, as React 17 does
400
+ if (react >= 17 && rtl >= 11) return {events: SIMULATED_EVENTS, attached: false};
401
+ if ((react === 15 || react === 16) && rtl >= 10) return {events: new Set([...SIMULATED_EVENTS].filter(event => !HOVER_EVENTS.has(event))), attached: true};
402
+ return {events: new Set(), attached: false};
147
403
  }
148
404
 
149
405
  /** The React major as {@link reactMajor} reads it, and the major of the RTL the tests run with. */
150
- function compatibility(packages: Packages, sourcePath: string, addsRtl: boolean): {react: number, rtl: number} {
406
+ function compatibility(packages: Packages, sourcePath: string, landed: ReadonlySet<string>): {react: number, rtl: number} {
151
407
  const roots = [...packages.keys()].filter(root => sourcePath.startsWith(root)).sort((a, b) => b.length - a.length);
152
408
  const declared = (name: "react" | "reactDom" | "rtl", from = roots) =>
153
409
  from.map(root => packages.get(root)![name]).find(version => version !== undefined);
154
410
  const supportedReact = (version: Declaration): version is DeclaredVersion => typeof version === "object" &&
155
- (version.major === 17 || (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);
156
412
  const react = declared("react");
157
413
  const rtl = declared("rtl");
158
414
  const enzyme = roots.findIndex(root => packages.get(root)!.enzyme);
159
- const added = addsRtl && rtl === undefined && enzyme >= 0 && packages.get(roots[enzyme])!.lockfileRegenerated &&
160
- supportedReact(declared("react", roots.slice(enzyme))) && 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));
161
420
  // RTL renders with the React DOM it resolves from its own package
162
- const rtlRoot = added ? enzyme : roots.findIndex(root => packages.get(root)!.rtl !== undefined);
163
- 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");
164
423
  // `render` with a container, `rerender`, `unmount`, and `fireEvent` are all there since RTL 10
165
- const rtlMajor = added ? 12 : typeof rtl === "object" && rtl.major >= 10 && rtl.major <= 12 ? rtl.major : 0;
166
- const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major && rtlMajor > 0;
424
+ const rtlMajor = added ? ((enzymeReact as DeclaredVersion).major >= 18 ? 16 : 12) : typeof rtl === "object" && rtl.major >= 10 && rtl.major <= 16 ? rtl.major : 0;
425
+ const compatible = supportedReact(react) && supportedReact(reactDom) && react.major === reactDom.major &&
426
+ rtlMajor > 0 && rtlSupports(rtlMajor, react.major);
167
427
  return {react: compatible ? react.major : 0, rtl: rtlMajor};
168
428
  }
169
429
 
430
+ /**
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.
448
+ */
449
+ function rtlSupports(rtl: number, react: number): boolean {
450
+ if (react === 15) return rtl === 12;
451
+ return react <= 17 ? rtl <= 12 : rtl === 16;
452
+ }
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
+
170
468
  /**
171
469
  * A version or a range within a single major: `16.14.0`, `^16.14`, `~16.9.0`, `16.9.x`, or `^17`,
172
470
  * whose minor version is known only where it is a lower bound.
@@ -205,9 +503,9 @@ function declaredVersion(version: string | undefined): Declaration {
205
503
  */
206
504
 
207
505
  export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
208
- readonly name = "org.openrewrite.react.migrate.enzyme-to-react-testing-library";
209
- readonly displayName = "Migrate Enzyme to React Testing Library";
210
- readonly description = "Migrates Enzyme `mount` wrappers whose every use is a supported DOM read or event (`find(selector).length`, `.exists()`, `.text()`, `.html()`, `.hasClass()`, positions through `.at(n)`, `.first()`, `.last()`, the wrapper's `text()` and `exists(selector)`, found nodes as a `toHaveLength` subject, `setProps` as a rerender of the cloned element, and on React 17 `simulate` with common mouse, keyboard, focus, form, and touch events, including `nativeEvent` mocks) and bare `mount` statements to React Testing Library container queries, `rerender`, and `fireEvent` in packages using React 16.9+/17 with RTL 10 to 12, adding RTL 12 where it is missing. 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.";
506
+ readonly name: string = "org.openrewrite.react.migrate.enzyme-to-react-testing-library";
507
+ readonly displayName: string = "Migrate Enzyme to React Testing Library";
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.";
211
509
 
212
510
  @Option({
213
511
  displayName: "Convert positions into untagged selector matches",
@@ -216,10 +514,22 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
216
514
  })
217
515
  untaggedSelectorPositions?: boolean;
218
516
 
517
+ // The editor reads where it added RTL, so this is the instance the run prepares as a child
518
+ private readonly forecast: ConversionForecast = {};
519
+
520
+ // PERF: the sources that import Enzyme, kept from the scan to the forecast in `generate`, as the dependency steps keep
521
+ // their manifests. Not in the accumulator, which the host keeps until the cycle ends; cleared once the forecast is made.
522
+ private readonly tests: JS.CompilationUnit[] = [];
523
+ private readonly dependencySteps = ADDS_RTL ? {rtl: new AddTestingLibraryReact(this.forecast), rtl18: new AddTestingLibraryReact18(this.forecast),
524
+ dom18: new AddTestingLibraryDom18(this.forecast)} : undefined;
525
+
219
526
  constructor(options?: {untaggedSelectorPositions?: boolean}) {
220
527
  super(options);
221
528
  }
222
529
 
530
+ /** Whether snapshot assertions of a wrapper convert, recording a new snapshot of the DOM; see {@link EnzymeSnapshotsToReactTestingLibrary}. */
531
+ protected readonly snapshots: boolean = false;
532
+
223
533
  private readonly usages = new DataTable<EnzymeUsageRow>(
224
534
  ENZYME_USAGE_TABLE, "Enzyme migration inventory",
225
535
  "Remaining Enzyme usages and migration actions. Module rows include references whose call types may be unavailable; they are not counts of test cases.",
@@ -227,14 +537,23 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
227
537
  );
228
538
 
229
539
  initialValue(): Scanned {
230
- return {packages: new Map(), components: new Map()};
540
+ this.tests.length = 0;
541
+ return {packages: new Map(), components: new Map(), modules: new Map(), names: new Map(), nullSnapshots: new Set()};
231
542
  }
232
543
 
233
544
  // The host may prepare the visitors before there is an accumulator, so it is read only while visiting
234
545
  async scanner(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
546
+ const steps = this.dependencySteps;
547
+ const tests = this.tests;
548
+ let converting: Promise<ReadonlySet<string>> | undefined;
549
+ // PERF: a second pass of the editor over the sources that import Enzyme, once, for all three steps
550
+ this.forecast.converting = steps && (() => converting ??= this.dryRun(scanned, rtlLanded(steps.rtl.candidates(), steps.rtl18.candidates(), steps.dom18.candidates())));
235
551
  const sources = new class extends JavaScriptVisitor<ExecutionContext> {
236
552
  override async visitJsCompilationUnit(cu: JS.CompilationUnit): Promise<J | undefined> {
237
553
  scanned.components.set(cu.sourcePath, hostComponentExports(cu));
554
+ scanned.modules.set(cu.sourcePath, moduleFacts(cu));
555
+ scanned.names.set(cu.sourcePath, selectorNames(cu));
556
+ if (importBindings(cu).some(({module}) => module === ENZYME)) tests.push(cu);
238
557
  return cu;
239
558
  }
240
559
  }();
@@ -260,22 +579,62 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
260
579
  reactDom: declaredVersion(version("react-dom")),
261
580
  rtl: declaredVersion(version(RTL)),
262
581
  enzyme: dependencies.some(dep => dep.name === "enzyme"),
263
- lockfileRegenerated: resolution?.packageManager !== "Pnpm" && resolution?.packageManager !== "Bun"
582
+ name: resolution?.name,
583
+ members: new Set((resolution?.workspacePackagePaths ?? []).map(member => member.replace(/^\.\//, "").slice(0, -"package.json".length))),
584
+ dependencies: new Set(dependencies.map(dep => dep.name)),
585
+ rootStyles: (resolution?.resolvedDependencies ?? []).some(dep => {
586
+ const range = ROOT_STYLES.get(dep.name);
587
+ return range !== undefined && valid(dep.version) !== null && satisfies(dep.version, range);
588
+ }),
589
+ optionalChaining: optionalChainingOf(name => dependencies.some(dep => dep.name === name), name => declaredVersion(version(name)))
264
590
  });
265
591
  return doc;
266
592
  }
267
593
  }();
268
- return new class extends TreeVisitor<any, ExecutionContext> {
594
+ const scan = new class extends TreeVisitor<any, ExecutionContext> {
595
+ override async isAcceptable(sourceFile: SourceFile): Promise<boolean> {
596
+ return isPlainText(sourceFile) && SNAPSHOT_FILE.test(sourceFile.sourcePath) || await manifests.isAcceptable(sourceFile) || await sources.isAcceptable(sourceFile);
597
+ }
598
+
269
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
+ }
270
604
  if (tree.kind === Json.Kind.Document) return await manifests.visit(tree, ctx, parent) as R | undefined;
271
605
  return tree.kind === JS.Kind.CompilationUnit ? await sources.visit(tree, ctx, parent) as R | undefined : tree as R;
272
606
  }
273
607
  }();
608
+ // HACK: the host infers which trees to send only from a JsonVisitor or JavaScriptVisitor, and sends a
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());
274
618
  }
275
619
 
276
620
  async editorWithData(scanned: Scanned): Promise<TreeVisitor<any, ExecutionContext>> {
621
+ return this.conversionEditor(scanned);
622
+ }
623
+
624
+ /** The sources the editor converts where RTL lands in every package root of `landed`, recording no rows. */
625
+ private async dryRun(scanned: Scanned, landed: ReadonlySet<string>): Promise<ReadonlySet<string>> {
626
+ const dry: DryRun = {landed, converted: new Set()};
627
+ const editor = await this.conversionEditor(scanned, dry);
628
+ const ctx = new ExecutionContext();
629
+ for (const cu of this.tests) await editor.visit(cu, ctx);
630
+ this.tests.length = 0;
631
+ return dry.converted;
632
+ }
633
+
634
+ private async conversionEditor(scanned: Scanned, dry?: DryRun): Promise<TreeVisitor<any, ExecutionContext>> {
277
635
  const jsx = capture<Expression>({name: "element", constraint: node => node.kind !== JS.Kind.Spread});
278
- const selector = capture<J.Literal>({name: "selector", constraint: node => selectorLiteral(node)});
636
+ const hostNames = (names: readonly string[]) => hostOnlyNames(names, scanned.names);
637
+ const selector = capture<J.Literal>({name: "selector", constraint: node => selectorLiteral(node, hostNames)});
279
638
  const after = {context: [`import {render} from "${RTL}";`], dependencies: {[RTL]: "12.1.5", "@types/react": "16.14.62"}};
280
639
  const patterns = (api: Render) => {
281
640
  const before = {lenientTypeMatching: false, context: [`import {${api}} from "enzyme";`], dependencies: {"@types/enzyme": "3.10.19", "@types/react": "16.14.62"}};
@@ -301,6 +660,10 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
301
660
  mount: rewrite(() => ({
302
661
  before: from.render,
303
662
  after: template`render(${jsx}, ${options})`.configure(after)
663
+ })),
664
+ attachedMount: rewrite(() => ({
665
+ before: from.render,
666
+ after: template`render(${jsx})`.configure(after)
304
667
  }))
305
668
  };
306
669
  };
@@ -309,11 +672,16 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
309
672
  "globalThis.document": {mount: renderRules("globalThis.document", "mount"), shallow: renderRules("globalThis.document", "shallow")}
310
673
  };
311
674
  const usages = this.usages;
675
+ const steps = this.dependencySteps;
312
676
  const untaggedPositions = this.untaggedSelectorPositions !== false;
677
+ const snapshots = this.snapshots;
313
678
  return check(and(not(isVendoredOrBundled()), or(usesMethod("enzyme mount(..)"), usesMethod("enzyme shallow(..)"))), new class extends JavaScriptVisitor<ExecutionContext> {
314
679
  private enabled = false;
315
680
  private reactMajor = 0;
316
- private events = false;
681
+ private events: SimulatedEvents = {events: new Set(), attached: false};
682
+ private rootStyles = false;
683
+ private optionalChaining = true;
684
+ private nullSnapshots = false;
317
685
  private typescript = false;
318
686
  private sourcePath = "";
319
687
  private readonly mounts = new Map<string, ConvertedRender>();
@@ -328,6 +696,8 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
328
696
  private readonly hoists = new Map<string, HoistedElement>();
329
697
  private readonly hoistedMounts = new Map<string, string>();
330
698
  private names: ReadonlySet<string> = new Set();
699
+ private cu?: JS.CompilationUnit;
700
+ private readonly portals = new Set<string>();
331
701
  private readonly rows: EnzymeUsageRow[] = [];
332
702
  private prettier = false;
333
703
  private printWidth = 80;
@@ -340,18 +710,36 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
340
710
  this.rows.length = 0;
341
711
  this.names = namesUsedIn(cu);
342
712
  const prettierStyle = findMarker<PrettierStyle>(cu, StyleKind.PrettierStyle);
343
- this.prettier = prettierStyle !== undefined;
713
+ this.prettier = prettierStyle !== undefined && !prettierStyle.ignored && await formattedBy(cu, prettierStyle);
344
714
  this.printWidth = typeof prettierStyle?.config.printWidth === "number" ? prettierStyle.config.printWidth : 80;
345
- this.reactMajor = reactMajor(scanned.packages, cu.sourcePath, ADDS_RTL);
346
- this.events = simulatesEvents(scanned.packages, cu.sourcePath, ADDS_RTL);
715
+ const landed = dry ? dry.landed : steps ? rtlLanded(steps.rtl.landed, steps.rtl18.landed, steps.dom18.landed) : undefined;
716
+ this.reactMajor = reactMajor(scanned.packages, cu.sourcePath, landed);
717
+ this.events = simulatesEvents(scanned.packages, cu.sourcePath, landed);
718
+ this.rootStyles = injectsRootStyles(scanned.packages, cu.sourcePath);
719
+ this.nullSnapshots = scanned.nullSnapshots.has(cu.sourcePath);
347
720
  this.typescript = isTypeScript(cu);
721
+ this.optionalChaining = parsesOptionalChaining(scanned.packages, cu.sourcePath, this.typescript);
348
722
  this.enabled = this.reactMajor > 0 && moduleBindings(this).moduleSystem === "esm";
349
723
  if (!this.enabled) return cu;
350
724
  this.imports = relativeImports(cu, scanned.components);
351
725
  this.importedNames = importedNames(cu);
352
- const visited = await super.visitJsCompilationUnit(cu, ctx);
353
- this.rows.forEach(row => usages.insertRow(ctx, row));
354
- return visited;
726
+ // Templates lay out what they insert with the source's Prettier style, which a source its config does not lay out keeps out of
727
+ const foreign = prettierStyle !== undefined && !this.prettier;
728
+ const visiting = foreign ? create(cu, draft => {
729
+ draft.markers.markers = draft.markers.markers.filter(marker => marker.kind !== StyleKind.PrettierStyle);
730
+ }) : cu;
731
+ // Templates find the style through the cursor, which `visit` set to the source as it came
732
+ if (foreign) this.cursor = new Cursor(visiting, this.cursor.parent);
733
+ this.cu = cu;
734
+ this.portals.clear();
735
+ const visited = await super.visitJsCompilationUnit(visiting, ctx);
736
+ if (dry) {
737
+ if (this.rows.some(row => row.status === "CONVERTED")) dry.converted.add(cu.sourcePath);
738
+ } else this.rows.forEach(row => usages.insertRow(ctx, row));
739
+ if (!foreign || !visited) return visited;
740
+ return visited === visiting ? cu : create(visited as JS.CompilationUnit, draft => {
741
+ draft.markers.markers.push(prettierStyle as any);
742
+ });
355
743
  }
356
744
 
357
745
  override async visitBlock(block: J.Block, ctx: ExecutionContext): Promise<J | undefined> {
@@ -362,13 +750,18 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
362
750
  if (!candidate) continue;
363
751
  const api = candidate.render;
364
752
  const reads = READS[api];
365
- const scope = analyzeWrapperScope(this.cursor, candidate, {events: this.events && reads.simulate, html: reads.html, untaggedPositions});
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,
756
+ constant: node => this.constantString(node)});
366
757
  if (!scope) continue;
367
758
  if ([...scope.uses.values()].some(use => use.use === "setProps" && !reads.props(use.props!, this.importedNames))) continue;
368
759
  const mount = new Cursor(candidate.mount, variableCursor(this.cursor, candidate.declaration));
369
760
  const document = documentAt(mount);
370
761
  if (!document || !await renderPatterns[api].render.match(candidate.mount, mount)) continue;
371
- this.mounts.set(candidate.mount.id, {document, api});
762
+ const attached = this.events.attached && [...scope.uses.values()].some(use => use.use === "simulate");
763
+ if (!attached && this.rootStyles && [...scope.uses.values()].some(use => CONTAINER_READS.has(use.use))) continue;
764
+ this.mounts.set(candidate.mount.id, {document, api, attached});
372
765
  apis.push(api);
373
766
  this.declarations.add(candidate.declaration.id);
374
767
  scope.uses.forEach((use, id) => this.uses.set(id, use));
@@ -481,13 +874,13 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
481
874
  if (mounted) {
482
875
  const hoisted = this.hoistedMounts.get(method.id);
483
876
  const result = hoisted ?
484
- await this.applyTemplate(Template.builder().code(`render(${hoisted}, ${renderOptions(mounted.document)})`).build().configure(after), visited) :
485
- await rules[mounted.document][mounted.api].mount.tryOn(this.cursor, visited, {visitor: this});
877
+ await this.applyTemplate(Template.builder().code(mounted.attached ? `render(${hoisted})` : `render(${hoisted}, ${renderOptions(mounted.document)})`).build().configure(after), visited) :
878
+ await rules[mounted.document][mounted.api][mounted.attached ? "attachedMount" : "mount"].tryOn(this.cursor, visited, {visitor: this});
486
879
  if (!result) return visited;
487
880
  this.pending.delete(method.id);
488
881
  return withRenderOptionsOnElementLine(result, ctx);
489
882
  }
490
- const statementOf = mountedElement(visited) && statementPosition(this.cursor) ? this.renderOf(visited) : undefined;
883
+ const statementOf = mountedElement(visited) && statementPosition(this.cursor) && !passesRef(visited) ? this.renderOf(visited, false) : undefined;
491
884
  const statement = statementOf && await this.tryInline(statementOf, "mount", visited, statementOf, enclosingScope(this.cursor), "MOUNT_STATEMENT", ctx);
492
885
  if (statement) return statement;
493
886
  const existsOf = visited.name.simpleName === "exists" && simpleChain(visited) ? this.renderOf(innermostCall(visited)) : undefined;
@@ -555,13 +948,28 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
555
948
  // An element's text content is never null, though its type allows it
556
949
  case "text":
557
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
558
952
  case "selectorText":
559
- 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();
560
954
  return element(false).code("?.textContent").build();
561
- case "html":
562
- return element(!!read.unasserted).code(read.unasserted ? ".outerHTML" : "?.outerHTML").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
+ }
966
+ case "node":
967
+ return element(true).build();
563
968
  case "hasClass":
564
969
  return element(true).code(".classList.contains(").param(read.className!).code(")").build();
970
+ // RTL's fragment holds the rendered DOM, which Jest serializes in place of Enzyme's tree
971
+ case "snapshot":
972
+ return code.code("expect(").param(read.wrapper).code(".asFragment())").build();
565
973
  case "setProps":
566
974
  code.param(read.wrapper).code(`.rerender(${read.reassigned ? `(${read.element} = ` : ""}cloneElement(${read.element}, `);
567
975
  return code.param(read.props!).code(read.reassigned ? ")))" : "))").build().configure({
@@ -592,24 +1000,63 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
592
1000
  }
593
1001
 
594
1002
  /**
595
- * The Enzyme render a call is, where RTL's `render` renders the same DOM: any `mount`, and a
596
- * `shallow` of a component that renders host elements only, as {@link rendersHostElements} decides.
1003
+ * The Enzyme render a call is, where RTL's `render` renders the same DOM: a `mount`, unless its
1004
+ * wrapper is `read` and a component it renders may render into a portal, and a `shallow` of a
1005
+ * component that renders host elements only, as {@link rendersHostElements} decides.
597
1006
  */
598
- private renderOf(node: J | undefined): Render | undefined {
1007
+ private renderOf(node: J | undefined, read = true): Render | undefined {
599
1008
  if (node?.kind !== J.Kind.MethodInvocation) return undefined;
600
1009
  const call = node as J.MethodInvocation;
601
1010
  const api = enzymeMethod(call);
602
- if (api === "mount") return api;
1011
+ if (api === "mount") return read && this.rendersPortal(call) ? undefined : api;
603
1012
  const element = call.arguments.elements[0]?.element;
604
1013
  return api === "shallow" && call.arguments.elements.length === 1 && rendersHostElements(element, this.imports, scanned.components, this.importedNames) ? api : undefined;
605
1014
  }
606
1015
 
1016
+ /**
1017
+ * Whether a component that a `mount` renders may render into a portal. Enzyme finds portal content
1018
+ * in the wrapper, and RTL's container does not hold it, so a converted read would count none and
1019
+ * an assertion of its absence would hold vacuously.
1020
+ */
1021
+ private rendersPortal(call: J.MethodInvocation): boolean {
1022
+ const element = call.arguments.elements[0]?.element;
1023
+ const {roots, declares, resolve} = this.moduleResolution();
1024
+ const portal = !!element && !!this.cu && rendersPortal(element, this.cu, {
1025
+ sourcePath: this.sourcePath,
1026
+ modules: scanned.modules,
1027
+ resolve,
1028
+ declares,
1029
+ packagePortals: () => [...scanned.modules].some(([path, facts]) => facts.portal &&
1030
+ path.startsWith(roots[0] ?? "") && !/(^|\/)__tests?__\/|\.(test|spec)\.[cm]?[jt]sx?$/.test(path))
1031
+ });
1032
+ if (portal && !this.portals.has(call.id)) {
1033
+ this.portals.add(call.id);
1034
+ this.rows.push({sourcePath: this.sourcePath, scope: enclosingScope(this.cursor), api: "mount", status: "REVIEW", reason: "PORTAL",
1035
+ suggestedAction: "A component it renders may render into a portal, which RTL renders outside the container: query `screen` or `baseElement` for that content."});
1036
+ }
1037
+ return portal;
1038
+ }
1039
+
1040
+ /** How the test's module specifiers resolve: from the packages enclosing it, as {@link resolver} does. */
1041
+ private moduleResolution() {
1042
+ const roots = [...scanned.packages.keys()].filter(root => this.sourcePath.startsWith(root)).sort((a, b) => b.length - a.length);
1043
+ const declares = (name: string) => roots.some(root => scanned.packages.get(root)!.dependencies.has(name));
1044
+ return {roots, declares, resolve: resolver(scanned.modules, [...new Set([...roots, ""])], declares)};
1045
+ }
1046
+
1047
+ /** The string a template of `const` strings holds, from the test or the modules it imports them from. */
1048
+ private constantString(node: J): string | undefined {
1049
+ const parts = stringParts(node);
1050
+ return parts && evaluate(parts, this.sourcePath, scanned.modules, this.moduleResolution().resolve);
1051
+ }
1052
+
607
1053
  private laidOutByPrettier(node: J): void {
608
1054
  if (this.prettier) this.reformat.add(node.id);
609
1055
  }
610
1056
 
611
1057
  private converted(api: string, scope: string, reason: string): void {
612
1058
  maybeRemoveImport(this, ENZYME);
1059
+ if (snapshots) maybeRemoveImport(this, "enzyme-to-json");
613
1060
  this.rows.push({sourcePath: this.sourcePath, scope, api, status: "CONVERTED", reason,
614
1061
  suggestedAction: "Run the migrated test and review whether an accessible RTL query would better express its intent."});
615
1062
  }
@@ -617,6 +1064,19 @@ export class EnzymeToReactTestingLibrary extends ScanningRecipe<Scanned> {
617
1064
  }
618
1065
 
619
1066
  async recipeList() {
620
- return [...ADDS_RTL ? [await addDependency(RTL_ADDITION)] : [], new FindEnzymeUsage()];
1067
+ const steps = this.dependencySteps;
1068
+ return [...steps ? [steps.rtl, steps.rtl18, steps.dom18] : [], new FindEnzymeUsage()];
621
1069
  }
622
1070
  }
1071
+
1072
+ /**
1073
+ * {@link EnzymeToReactTestingLibrary}, also converting snapshot assertions of the wrappers it converts. RTL
1074
+ * snapshots the rendered DOM, which Enzyme's serializer records as a component tree, so every converted
1075
+ * snapshot is written anew on the next run with `--updateSnapshot` and should be reviewed then.
1076
+ */
1077
+ export class EnzymeSnapshotsToReactTestingLibrary extends EnzymeToReactTestingLibrary {
1078
+ override readonly name = "org.openrewrite.react.migrate.enzyme-snapshots-to-react-testing-library";
1079
+ override readonly displayName = "Migrate Enzyme to React Testing Library, snapshots included";
1080
+ override readonly description = "Migrates Enzyme wrappers as `org.openrewrite.react.migrate.enzyme-to-react-testing-library` does, and also converts `expect(wrapper).toMatchSnapshot()` and `expect(toJson(wrapper)).toMatchSnapshot()` of those wrappers to `expect(wrapper.asFragment()).toMatchSnapshot()`, removing the `enzyme-to-json` import where nothing else uses it. RTL snapshots the rendered DOM where Enzyme's serializer recorded a component tree, so the stored snapshots of converted tests no longer match: run the tests with `--updateSnapshot` once and review the new snapshots. Inline snapshots and snapshots of shallow renders that are not converted are left for review.";
1081
+ protected override readonly snapshots: boolean = true;
1082
+ }