@openrewrite/recipes-angular 1.35.0 → 1.38.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 (130) hide show
  1. package/dist/index.d.ts +8 -0
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js +38 -6
  4. package/dist/index.js.map +1 -1
  5. package/dist/libraries/components/package-version.d.ts +1 -1
  6. package/dist/libraries/components/package-version.d.ts.map +1 -1
  7. package/dist/libraries/components/package-version.js +1 -1
  8. package/dist/libraries/components/package-version.js.map +1 -1
  9. package/dist/migration/add-static-false-to-view-queries.d.ts.map +1 -1
  10. package/dist/migration/add-static-false-to-view-queries.js +16 -13
  11. package/dist/migration/add-static-false-to-view-queries.js.map +1 -1
  12. package/dist/migration/angular-version.d.ts +22 -2
  13. package/dist/migration/angular-version.d.ts.map +1 -1
  14. package/dist/migration/angular-version.js +65 -18
  15. package/dist/migration/angular-version.js.map +1 -1
  16. package/dist/migration/jasmine-to-vitest/add-vitest-imports.d.ts +11 -0
  17. package/dist/migration/jasmine-to-vitest/add-vitest-imports.d.ts.map +1 -0
  18. package/dist/migration/jasmine-to-vitest/add-vitest-imports.js +76 -0
  19. package/dist/migration/jasmine-to-vitest/add-vitest-imports.js.map +1 -0
  20. package/dist/migration/jasmine-to-vitest/migrate-fake-async.d.ts +14 -0
  21. package/dist/migration/jasmine-to-vitest/migrate-fake-async.d.ts.map +1 -0
  22. package/dist/migration/jasmine-to-vitest/migrate-fake-async.js +225 -0
  23. package/dist/migration/jasmine-to-vitest/migrate-fake-async.js.map +1 -0
  24. package/dist/migration/jasmine-to-vitest/migrate-jasmine-lifecycle.d.ts +11 -0
  25. package/dist/migration/jasmine-to-vitest/migrate-jasmine-lifecycle.d.ts.map +1 -0
  26. package/dist/migration/jasmine-to-vitest/migrate-jasmine-lifecycle.js +379 -0
  27. package/dist/migration/jasmine-to-vitest/migrate-jasmine-lifecycle.js.map +1 -0
  28. package/dist/migration/jasmine-to-vitest/migrate-jasmine-matchers.d.ts +18 -0
  29. package/dist/migration/jasmine-to-vitest/migrate-jasmine-matchers.d.ts.map +1 -0
  30. package/dist/migration/jasmine-to-vitest/migrate-jasmine-matchers.js +446 -0
  31. package/dist/migration/jasmine-to-vitest/migrate-jasmine-matchers.js.map +1 -0
  32. package/dist/migration/jasmine-to-vitest/migrate-jasmine-misc.d.ts +11 -0
  33. package/dist/migration/jasmine-to-vitest/migrate-jasmine-misc.d.ts.map +1 -0
  34. package/dist/migration/jasmine-to-vitest/migrate-jasmine-misc.js +209 -0
  35. package/dist/migration/jasmine-to-vitest/migrate-jasmine-misc.js.map +1 -0
  36. package/dist/migration/jasmine-to-vitest/migrate-jasmine-spies.d.ts +11 -0
  37. package/dist/migration/jasmine-to-vitest/migrate-jasmine-spies.d.ts.map +1 -0
  38. package/dist/migration/jasmine-to-vitest/migrate-jasmine-spies.js +567 -0
  39. package/dist/migration/jasmine-to-vitest/migrate-jasmine-spies.js.map +1 -0
  40. package/dist/migration/jasmine-to-vitest/migrate-jasmine-to-vitest.d.ts +16 -0
  41. package/dist/migration/jasmine-to-vitest/migrate-jasmine-to-vitest.d.ts.map +1 -0
  42. package/dist/migration/jasmine-to-vitest/migrate-jasmine-to-vitest.js +90 -0
  43. package/dist/migration/jasmine-to-vitest/migrate-jasmine-to-vitest.js.map +1 -0
  44. package/dist/migration/jasmine-to-vitest/migrate-jasmine-types.d.ts +11 -0
  45. package/dist/migration/jasmine-to-vitest/migrate-jasmine-types.d.ts.map +1 -0
  46. package/dist/migration/jasmine-to-vitest/migrate-jasmine-types.js +142 -0
  47. package/dist/migration/jasmine-to-vitest/migrate-jasmine-types.js.map +1 -0
  48. package/dist/migration/jasmine-to-vitest/support.d.ts +88 -0
  49. package/dist/migration/jasmine-to-vitest/support.d.ts.map +1 -0
  50. package/dist/migration/jasmine-to-vitest/support.js +561 -0
  51. package/dist/migration/jasmine-to-vitest/support.js.map +1 -0
  52. package/dist/migration/remove-default-project.d.ts +1 -0
  53. package/dist/migration/remove-default-project.d.ts.map +1 -1
  54. package/dist/migration/remove-default-project.js +3 -1
  55. package/dist/migration/remove-default-project.js.map +1 -1
  56. package/dist/migration/upgrade-to-angular-10.d.ts.map +1 -1
  57. package/dist/migration/upgrade-to-angular-10.js +3 -2
  58. package/dist/migration/upgrade-to-angular-10.js.map +1 -1
  59. package/dist/migration/upgrade-to-angular-11.d.ts.map +1 -1
  60. package/dist/migration/upgrade-to-angular-11.js +3 -2
  61. package/dist/migration/upgrade-to-angular-11.js.map +1 -1
  62. package/dist/migration/upgrade-to-angular-12.d.ts.map +1 -1
  63. package/dist/migration/upgrade-to-angular-12.js +3 -2
  64. package/dist/migration/upgrade-to-angular-12.js.map +1 -1
  65. package/dist/migration/upgrade-to-angular-13.d.ts.map +1 -1
  66. package/dist/migration/upgrade-to-angular-13.js +4 -5
  67. package/dist/migration/upgrade-to-angular-13.js.map +1 -1
  68. package/dist/migration/upgrade-to-angular-14.d.ts.map +1 -1
  69. package/dist/migration/upgrade-to-angular-14.js +6 -2
  70. package/dist/migration/upgrade-to-angular-14.js.map +1 -1
  71. package/dist/migration/upgrade-to-angular-15.d.ts.map +1 -1
  72. package/dist/migration/upgrade-to-angular-15.js +3 -2
  73. package/dist/migration/upgrade-to-angular-15.js.map +1 -1
  74. package/dist/migration/upgrade-to-angular-16.d.ts.map +1 -1
  75. package/dist/migration/upgrade-to-angular-16.js +3 -2
  76. package/dist/migration/upgrade-to-angular-16.js.map +1 -1
  77. package/dist/migration/upgrade-to-angular-17.d.ts.map +1 -1
  78. package/dist/migration/upgrade-to-angular-17.js +3 -2
  79. package/dist/migration/upgrade-to-angular-17.js.map +1 -1
  80. package/dist/migration/upgrade-to-angular-18.d.ts.map +1 -1
  81. package/dist/migration/upgrade-to-angular-18.js +3 -2
  82. package/dist/migration/upgrade-to-angular-18.js.map +1 -1
  83. package/dist/migration/upgrade-to-angular-19.d.ts.map +1 -1
  84. package/dist/migration/upgrade-to-angular-19.js +3 -2
  85. package/dist/migration/upgrade-to-angular-19.js.map +1 -1
  86. package/dist/migration/upgrade-to-angular-20.d.ts.map +1 -1
  87. package/dist/migration/upgrade-to-angular-20.js +3 -2
  88. package/dist/migration/upgrade-to-angular-20.js.map +1 -1
  89. package/dist/migration/upgrade-to-angular-21.d.ts.map +1 -1
  90. package/dist/migration/upgrade-to-angular-21.js +3 -2
  91. package/dist/migration/upgrade-to-angular-21.js.map +1 -1
  92. package/dist/migration/upgrade-to-angular-22.d.ts.map +1 -1
  93. package/dist/migration/upgrade-to-angular-22.js +3 -2
  94. package/dist/migration/upgrade-to-angular-22.js.map +1 -1
  95. package/dist/migration/upgrade-to-angular-8.d.ts.map +1 -1
  96. package/dist/migration/upgrade-to-angular-8.js +3 -2
  97. package/dist/migration/upgrade-to-angular-8.js.map +1 -1
  98. package/dist/migration/upgrade-to-angular-9.d.ts.map +1 -1
  99. package/dist/migration/upgrade-to-angular-9.js +3 -2
  100. package/dist/migration/upgrade-to-angular-9.js.map +1 -1
  101. package/package.json +1 -1
  102. package/src/index.ts +24 -0
  103. package/src/libraries/components/package-version.ts +2 -2
  104. package/src/migration/add-static-false-to-view-queries.ts +16 -12
  105. package/src/migration/angular-version.ts +65 -16
  106. package/src/migration/jasmine-to-vitest/add-vitest-imports.ts +51 -0
  107. package/src/migration/jasmine-to-vitest/migrate-fake-async.ts +211 -0
  108. package/src/migration/jasmine-to-vitest/migrate-jasmine-lifecycle.ts +346 -0
  109. package/src/migration/jasmine-to-vitest/migrate-jasmine-matchers.ts +410 -0
  110. package/src/migration/jasmine-to-vitest/migrate-jasmine-misc.ts +190 -0
  111. package/src/migration/jasmine-to-vitest/migrate-jasmine-spies.ts +533 -0
  112. package/src/migration/jasmine-to-vitest/migrate-jasmine-to-vitest.ts +72 -0
  113. package/src/migration/jasmine-to-vitest/migrate-jasmine-types.ts +97 -0
  114. package/src/migration/jasmine-to-vitest/support.ts +516 -0
  115. package/src/migration/remove-default-project.ts +3 -1
  116. package/src/migration/upgrade-to-angular-10.ts +4 -3
  117. package/src/migration/upgrade-to-angular-11.ts +4 -3
  118. package/src/migration/upgrade-to-angular-12.ts +4 -3
  119. package/src/migration/upgrade-to-angular-13.ts +5 -6
  120. package/src/migration/upgrade-to-angular-14.ts +7 -3
  121. package/src/migration/upgrade-to-angular-15.ts +4 -3
  122. package/src/migration/upgrade-to-angular-16.ts +4 -3
  123. package/src/migration/upgrade-to-angular-17.ts +4 -3
  124. package/src/migration/upgrade-to-angular-18.ts +4 -3
  125. package/src/migration/upgrade-to-angular-19.ts +4 -3
  126. package/src/migration/upgrade-to-angular-20.ts +4 -3
  127. package/src/migration/upgrade-to-angular-21.ts +4 -3
  128. package/src/migration/upgrade-to-angular-22.ts +4 -3
  129. package/src/migration/upgrade-to-angular-8.ts +4 -3
  130. package/src/migration/upgrade-to-angular-9.ts +4 -3
@@ -0,0 +1,410 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ *
4
+ * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
+ */
6
+
7
+ import {Cursor, ExecutionContext, Option, Recipe, TreeVisitor} from "@openrewrite/rewrite";
8
+ import {J, isFieldAccess, isLiteral, isMethodInvocation} from "@openrewrite/rewrite/java";
9
+ import {JS} from "@openrewrite/rewrite/javascript";
10
+ import {create} from "mutative";
11
+ import {
12
+ JasmineToVitestVisitor,
13
+ Piece,
14
+ StatementResult,
15
+ args,
16
+ isGlobalCall,
17
+ isStringLiteral,
18
+ jasmineMethodName,
19
+ printTrimmed,
20
+ replaceWith,
21
+ select,
22
+ todoText,
23
+ unwrap
24
+ } from "./support";
25
+
26
+ /**
27
+ * @see https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/refactor/jasmine-vitest/transformers/jasmine-matcher.ts
28
+ */
29
+ export class MigrateJasmineMatchersToVitest extends Recipe {
30
+ readonly name = "org.openrewrite.angular.migration.migrate-jasmine-matchers-to-vitest";
31
+ readonly displayName = "Migrate Jasmine matchers to Vitest";
32
+ readonly description = "Rewrites the Jasmine matchers Vitest does not share: `toBeTrue()` and `toBeFalse()` become " +
33
+ "`toBe(true)` and `toBe(false)`, `toHaveSize` becomes `toHaveLength`, `jasmine.any` and the other asymmetric " +
34
+ "matchers move to `expect`, `expectAsync(...)` becomes `expect(...).resolves` or `.rejects`, `withContext(msg)` " +
35
+ "becomes `expect(actual, msg)`, `toHaveBeenCalledOnceWith` becomes `toHaveBeenCalledTimes(1)` and " +
36
+ "`toHaveBeenCalledWith`, and `toHaveClass`, `toBeNullish` and `toHaveBeenCalledBefore` become plain " +
37
+ "assertions. A matcher Vitest has no equivalent for is left with a `TODO: vitest-migration` comment, as the " +
38
+ "Angular CLI's `refactor-jasmine-vitest` schematic does.";
39
+
40
+ @Option({
41
+ displayName: "Browser mode",
42
+ description: "Whether the tests run in Vitest's browser mode, which has a `toHaveClass` matcher of its own. " +
43
+ "When they do, `toHaveClass` is left as it is.",
44
+ required: false,
45
+ example: "false"
46
+ })
47
+ browserMode?: boolean;
48
+
49
+ constructor(options?: { browserMode?: boolean }) {
50
+ super(options);
51
+ }
52
+
53
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
54
+ return new MatchersVisitor(!!this.browserMode);
55
+ }
56
+ }
57
+
58
+ const SUGAR = new Map<string, { name: string, args?: string }>([
59
+ ['toBeTrue', {name: 'toBe', args: 'true'}],
60
+ ['toBeFalse', {name: 'toBe', args: 'false'}],
61
+ ['toBePositiveInfinity', {name: 'toBe', args: 'Infinity'}],
62
+ ['toBeNegativeInfinity', {name: 'toBe', args: '-Infinity'}],
63
+ ['toHaveSize', {name: 'toHaveLength'}],
64
+ ]);
65
+
66
+ /** Matchers that take Jasmine's failure message after this many arguments; Vitest takes it in `expect`. */
67
+ const MESSAGE_ARITY = new Map<string, number>([
68
+ ['toBe', 1], ['toEqual', 1], ['toContain', 1], ['toMatch', 1], ['toBeInstanceOf', 1], ['toHaveSize', 1],
69
+ ['toBeGreaterThan', 1], ['toBeLessThan', 1], ['toBeGreaterThanOrEqual', 1], ['toBeLessThanOrEqual', 1],
70
+ ['toHaveBeenCalledTimes', 1],
71
+ ['toBeTruthy', 0], ['toBeFalsy', 0], ['toBeTrue', 0], ['toBeFalse', 0], ['toBeDefined', 0], ['toBeUndefined', 0],
72
+ ['toBeNull', 0], ['toBeNaN', 0], ['toHaveBeenCalled', 0],
73
+ ]);
74
+
75
+ /** A string, a template or a concatenation that starts with one. */
76
+ function isMessage(e: J): boolean {
77
+ const u = unwrap(e) ?? e;
78
+ if (isStringLiteral(u) || u.kind === JS.Kind.TemplateExpression) return true;
79
+ return u.kind === J.Kind.Binary && isMessage((u as J.Binary).left);
80
+ }
81
+
82
+ const ASYMMETRIC = ['anything', 'any', 'stringMatching', 'objectContaining', 'arrayContaining', 'stringContaining'];
83
+
84
+ const ASYNC = new Map<string, { base: 'resolves' | 'rejects', matcher: string, not?: boolean, keepArgs: boolean }>([
85
+ ['toBeResolved', {base: 'resolves', matcher: 'toThrow', not: true, keepArgs: false}],
86
+ ['toBeResolvedTo', {base: 'resolves', matcher: 'toEqual', keepArgs: true}],
87
+ ['toBeRejected', {base: 'rejects', matcher: 'toThrow', keepArgs: false}],
88
+ ['toBeRejectedWith', {base: 'rejects', matcher: 'toEqual', keepArgs: true}],
89
+ ['toBeRejectedWithError', {base: 'rejects', matcher: 'toThrowError', keepArgs: true}],
90
+ ]);
91
+
92
+ /** A matcher call, `expect(actual).not.matcher(...)` read apart. */
93
+ interface MatcherCall {
94
+ expect: J;
95
+ negated: boolean;
96
+ }
97
+
98
+ function matcherCall(m: J.MethodInvocation): MatcherCall | undefined {
99
+ let e = select(m);
100
+ let negated = false;
101
+ if (e && isFieldAccess(e) && e.name.element.simpleName === 'not') {
102
+ negated = true;
103
+ e = e.target;
104
+ }
105
+ return e ? {expect: e, negated} : undefined;
106
+ }
107
+
108
+ class MatchersVisitor extends JasmineToVitestVisitor {
109
+ constructor(private readonly browserMode: boolean) {
110
+ super();
111
+ }
112
+
113
+ protected override async visitMethodInvocation(method: J.MethodInvocation, p: ExecutionContext): Promise<J | undefined> {
114
+ const visited = await super.visitMethodInvocation(method, p);
115
+ if (!visited || !isMethodInvocation(visited)) return visited;
116
+ let m: J = visited;
117
+ const steps: ((m: J.MethodInvocation) => Promise<J | undefined> | J | undefined)[] = [
118
+ x => this.withContext(x),
119
+ x => this.expectationMessage(x),
120
+ x => this.expectAsync(x),
121
+ x => this.syntacticSugar(x),
122
+ x => this.complexMatchers(x),
123
+ x => this.asymmetric(x),
124
+ x => this.calledBefore(x),
125
+ x => this.browserMode ? undefined : this.toHaveClass(x),
126
+ x => this.toBeNullish(x),
127
+ ];
128
+ for (const step of steps) {
129
+ if (!isMethodInvocation(m)) break;
130
+ m = (await step(m)) ?? m;
131
+ }
132
+ return m;
133
+ }
134
+
135
+ /** `expect(a).withContext(msg).toBe(b)` to `expect(a, msg).toBe(b)`. */
136
+ private async withContext(m: J.MethodInvocation): Promise<J | undefined> {
137
+ // The chain between the matcher and the `withContext` call: `.not` and the like.
138
+ const chain: J.FieldAccess[] = [];
139
+ let e = select(m);
140
+ while (e && isFieldAccess(e)) {
141
+ chain.push(e);
142
+ e = e.target;
143
+ }
144
+ if (!e || !isMethodInvocation(e) || e.name.simpleName !== 'withContext') return undefined;
145
+ const withContext = e;
146
+ const expectCall = select(withContext);
147
+ if (!isGlobalCall(expectCall, 'expect')) return undefined;
148
+ const message = args(withContext)[0];
149
+ const links = chain.map(f => '.' + f.name.element.simpleName).reverse().join('');
150
+ const expectArgs = args(expectCall);
151
+ const newExpect: Piece[] = message
152
+ ? ['expect(', ...(expectArgs.length ? [expectArgs, ', '] : []), message, ')']
153
+ : ['expect(', expectArgs, ')'];
154
+ return replaceWith(m, this.cursor, ...newExpect, links, `.${m.name.simpleName}(`, args(m), ')');
155
+ }
156
+
157
+ /** `expect(a).toBe(b, msg)`, Jasmine's failure message as a last argument, to `expect(a, msg).toBe(b)`. */
158
+ private async expectationMessage(m: J.MethodInvocation): Promise<J | undefined> {
159
+ const arity = MESSAGE_ARITY.get(m.name.simpleName);
160
+ const a = args(m);
161
+ if (arity === undefined || a.length !== arity + 1 || !isMessage(a[arity])) return undefined;
162
+ const call = matcherCall(m);
163
+ if (!call || !isGlobalCall(call.expect as J, 'expect') || args(call.expect as J.MethodInvocation).length !== 1) return undefined;
164
+ const rest: Piece[] = [];
165
+ a.slice(0, arity).forEach((x, i) => rest.push(...(i ? [', ', x] : [x])));
166
+ return replaceWith(m, this.cursor, 'expect(', args(call.expect as J.MethodInvocation)[0], ', ', a[arity], ')',
167
+ call.negated ? '.not' : '', `.${m.name.simpleName}(`, ...rest, ')');
168
+ }
169
+
170
+ private async expectAsync(m: J.MethodInvocation): Promise<J | undefined> {
171
+ const expectCall = select(m);
172
+ if (!isGlobalCall(expectCall, 'expectAsync')) return undefined;
173
+ const name = m.name.simpleName;
174
+ const mapping = ASYNC.get(name);
175
+ if (mapping) {
176
+ const actual = args(expectCall)[0];
177
+ return replaceWith(m, this.cursor, 'expect(', ...(actual ? [actual] : []), `).${mapping.base}`,
178
+ mapping.not ? '.not' : '', `.${mapping.matcher}(`, mapping.keepArgs ? args(m) : [], ')');
179
+ }
180
+ if (name === 'toBePending') {
181
+ this.todo(m, 'Unsupported matcher ".toBePending()" found. Vitest does not have a direct equivalent. ' +
182
+ 'Please migrate this manually, for example by using `Promise.race` to check if the promise settles within a short timeout.');
183
+ } else {
184
+ this.todo(m, `Unsupported expectAsync matcher ".${name}()" found. Please migrate this manually.`);
185
+ }
186
+ return m;
187
+ }
188
+
189
+ private async syntacticSugar(m: J.MethodInvocation): Promise<J | undefined> {
190
+ const name = m.name.simpleName;
191
+ if (!m.select) return undefined;
192
+ if (name === 'toHaveSpyInteractions') {
193
+ this.todo(m, 'Unsupported matcher ".toHaveSpyInteractions()" found. ' +
194
+ 'Please migrate this manually by checking the `mock.calls.length` of the individual spies.');
195
+ return m;
196
+ }
197
+ if (name === 'toThrowMatching') {
198
+ this.todo(m, `Unsupported matcher ".${name}()" found. Please migrate this manually.`,
199
+ 'https://vitest.dev/api/expect.html#tothrowerror');
200
+ return m;
201
+ }
202
+ const mapping = SUGAR.get(name);
203
+ if (!mapping) return undefined;
204
+ return this.rebuildMatcher(m, mapping.name, mapping.args !== undefined ? [mapping.args] : [args(m)]);
205
+ }
206
+
207
+ /** The same receiver, its formatting kept, calling another matcher. */
208
+ private async rebuildMatcher(m: J.MethodInvocation, name: string, newArgs: Piece[], receiver?: J): Promise<J> {
209
+ const result = await replaceWith(m, this.cursor, receiver ?? select(m)!, `.${name}(`, ...newArgs, ')');
210
+ if (!receiver && isMethodInvocation(result) && result.select) {
211
+ return create(result, d => {
212
+ d.select = m.select as any;
213
+ });
214
+ }
215
+ return result;
216
+ }
217
+
218
+ /** `.toEqual(jasmine.truthy())` and its siblings, to Vitest's own matchers. */
219
+ private async complexMatchers(m: J.MethodInvocation): Promise<J | undefined> {
220
+ const a = args(m);
221
+ if (m.name.simpleName !== 'toEqual' || a.length !== 1) return undefined;
222
+ const jasmineMatcher = jasmineMethodName(a[0]);
223
+ if (!jasmineMatcher) return undefined;
224
+ let name: string | undefined;
225
+ let newArgs: Piece[] = [];
226
+ let negate = false;
227
+ switch (jasmineMatcher) {
228
+ case 'truthy':
229
+ name = 'toBeTruthy';
230
+ break;
231
+ case 'falsy':
232
+ name = 'toBeFalsy';
233
+ break;
234
+ case 'empty':
235
+ name = 'toHaveLength';
236
+ newArgs = ['0'];
237
+ break;
238
+ case 'notEmpty':
239
+ name = 'toHaveLength';
240
+ newArgs = ['0'];
241
+ negate = true;
242
+ break;
243
+ case 'is':
244
+ name = 'toBe';
245
+ newArgs = [args(a[0] as J.MethodInvocation)];
246
+ break;
247
+ }
248
+ if (!name) return undefined;
249
+ const call = matcherCall(m)!;
250
+ if (call.negated) negate = !negate;
251
+ return replaceWith(m, this.cursor, call.expect, negate ? '.not' : '', `.${name}(`, ...newArgs, ')');
252
+ }
253
+
254
+ /** `jasmine.any(String)` to `expect.any(String)`, and the other asymmetric matchers. */
255
+ private asymmetric(m: J.MethodInvocation): J | undefined {
256
+ const name = jasmineMethodName(m);
257
+ if (!name || !ASYMMETRIC.includes(name)) return undefined;
258
+ return create(m, d => {
259
+ (d.select!.element as any).simpleName = 'expect';
260
+ });
261
+ }
262
+
263
+ private async calledBefore(m: J.MethodInvocation): Promise<J | undefined> {
264
+ const a = args(m);
265
+ if (m.name.simpleName !== 'toHaveBeenCalledBefore' || a.length !== 1) return undefined;
266
+ const call = matcherCall(m);
267
+ if (!call || !isMethodInvocation(call.expect)) return undefined;
268
+ const spyA = args(call.expect)[0];
269
+ const order = (spy: J): Piece[] => ['Math.min(...vi.mocked(', spy, ').mock.invocationCallOrder)'];
270
+ return replaceWith(m, this.cursor, 'expect(', ...order(spyA), `).${call.negated ? 'toBeGreaterThanOrEqual' : 'toBeLessThan'}(`,
271
+ ...order(a[0]), ')');
272
+ }
273
+
274
+ private async toHaveClass(m: J.MethodInvocation): Promise<J | undefined> {
275
+ const a = args(m);
276
+ if (m.name.simpleName !== 'toHaveClass' || a.length !== 1) return undefined;
277
+ const call = matcherCall(m);
278
+ if (!call || !isMethodInvocation(call.expect)) return undefined;
279
+ const [element, message] = args(call.expect);
280
+ return replaceWith(m, this.cursor, 'expect(', element, '.classList.contains(', a[0], ')',
281
+ ...(message ? [', ', message] : []), `).toBe(${!call.negated})`);
282
+ }
283
+
284
+ private async toBeNullish(m: J.MethodInvocation): Promise<J | undefined> {
285
+ if (m.name.simpleName !== 'toBeNullish' || args(m).length !== 0) return undefined;
286
+ const call = matcherCall(m);
287
+ if (!call || !isMethodInvocation(call.expect)) return undefined;
288
+ const element = args(call.expect)[0];
289
+ return replaceWith(m, this.cursor, 'expect(', element, ' == null', `).toBe(${!call.negated})`);
290
+ }
291
+
292
+ protected override async visitBlockStatement(statement: J, cursor: Cursor): Promise<StatementResult | undefined> {
293
+ if (!isMethodInvocation(statement)) return undefined;
294
+ return (await this.calledOnceWith(statement, cursor))
295
+ ?? (await this.arrayWithExactContents(statement, cursor))
296
+ ?? (await this.expectNothing(statement, cursor));
297
+ }
298
+
299
+ private async calledOnceWith(m: J.MethodInvocation, cursor: Cursor): Promise<StatementResult | undefined> {
300
+ if (m.name.simpleName !== 'toHaveBeenCalledOnceWith' || !m.select) return undefined;
301
+ const expectCall = select(m)!;
302
+ // Split, a negated assertion would assert that neither holds instead of not both.
303
+ if (isFieldAccess(expectCall) && expectCall.name.element.simpleName === 'not') {
304
+ return {replace: [create(m, d => {
305
+ d.name.simpleName = 'toHaveBeenCalledExactlyOnceWith';
306
+ })]};
307
+ }
308
+ return {
309
+ replace: [
310
+ await replaceWith(m, cursor, expectCall, '.toHaveBeenCalledTimes(1)'),
311
+ await replaceWith(m, cursor, expectCall, '.toHaveBeenCalledWith(', args(m), ')'),
312
+ ]
313
+ };
314
+ }
315
+
316
+ /**
317
+ * `toEqual(jasmine.arrayWithExactContents([...]))` asserts the same elements in any order. A length check
318
+ * with `arrayContaining` is exactly that when the expected elements are distinct and compared by equality,
319
+ * since each then matches a different element of an array of the same length. Primitive literals of one
320
+ * type are compared through sorted copies instead when they repeat or the assertion is negated, because
321
+ * `[...actual].sort()` equals the sorted literals only for a permutation of them. Anything else, an
322
+ * asymmetric matcher, an object or a variable, keeps its TODO.
323
+ */
324
+ private async arrayWithExactContents(m: J.MethodInvocation, cursor: Cursor): Promise<StatementResult | undefined> {
325
+ const a = args(m);
326
+ if (m.name.simpleName !== 'toEqual' || a.length !== 1 || !m.select) return undefined;
327
+ const matcher = a[0];
328
+ if (jasmineMethodName(matcher) !== 'arrayWithExactContents' || args(matcher as J.MethodInvocation).length !== 1) {
329
+ return undefined;
330
+ }
331
+ const array = args(matcher as J.MethodInvocation)[0];
332
+ if (array.kind !== J.Kind.NewArray) {
333
+ this.todo(m, 'Cannot transform jasmine.arrayWithExactContents with a dynamic variable. Please migrate this manually.');
334
+ return undefined;
335
+ }
336
+ const elements = ((array as J.NewArray).initializer?.elements ?? []).map(e => e.element).filter(e => e.kind !== J.Kind.Empty);
337
+ const expectCall = select(m)!;
338
+ const negated = isFieldAccess(expectCall) && expectCall.name.element.simpleName === 'not';
339
+ const expectOf = negated ? (expectCall as J.FieldAccess).target : expectCall;
340
+ const actual = isGlobalCall(expectOf, 'expect') && args(expectOf).length === 1 ? args(expectOf)[0] : undefined;
341
+ const literals = sortableLiterals(elements);
342
+
343
+ if (literals && actual && (negated || literals.repeats)) {
344
+ return {
345
+ replace: [await replaceWith(m, cursor, 'expect([...', actual, '].sort())', negated ? '.not' : '',
346
+ `.toEqual([${literals.sorted.join(', ')}])`)]
347
+ };
348
+ }
349
+ if (negated) {
350
+ this.todo(m, 'Cannot transform a negated jasmine.arrayWithExactContents of these elements. Please migrate this manually.');
351
+ return undefined;
352
+ }
353
+ const lengthCheck = await replaceWith(m, cursor, expectCall, `.toHaveLength(${elements.length})`);
354
+ if (!literals) {
355
+ this.todo(lengthCheck, "Verify this matches strict array content (multiset equality). Vitest's arrayContaining is a subset check.");
356
+ }
357
+ return {
358
+ replace: [
359
+ lengthCheck,
360
+ await replaceWith(m, cursor, expectCall, '.toEqual(expect.arrayContaining(', array, '))'),
361
+ ]
362
+ };
363
+ }
364
+
365
+ /** `expect().nothing()` asserts nothing, and a Vitest test without assertions passes. */
366
+ private async expectNothing(m: J.MethodInvocation, cursor: Cursor): Promise<StatementResult | undefined> {
367
+ if (m.name.simpleName !== 'nothing') return undefined;
368
+ const expectCall = select(m);
369
+ if (!isGlobalCall(expectCall, 'expect') || args(expectCall).length > 0) return undefined;
370
+ return {
371
+ removeLeaving: [
372
+ todoText('expect().nothing() has been removed because it is redundant in Vitest. Tests without assertions pass by default.'),
373
+ ...await commentedOut(m, cursor),
374
+ ]
375
+ };
376
+ }
377
+ }
378
+
379
+ /** The statement's text as `//` comment lines, the way the schematic keeps what it removes. */
380
+ export async function commentedOut(statement: J, cursor: Cursor): Promise<string[]> {
381
+ let text = await printTrimmed(statement, cursor);
382
+ if (!text.endsWith(';') && !text.endsWith('}')) text += ';';
383
+ return text.split('\n').map(l => ` ${l.trim()}`);
384
+ }
385
+
386
+ /**
387
+ * The elements' source text in `Array.prototype.sort`'s order, when every element is a string, number or
388
+ * boolean literal of the same type, and whether any value repeats.
389
+ */
390
+ function sortableLiterals(elements: J[]): { sorted: string[], repeats: boolean } | undefined {
391
+ if (elements.length === 0) return undefined;
392
+ const values: { value: string | number | boolean, source: string }[] = [];
393
+ for (const e of elements) {
394
+ if (!isLiteral(e) || e.valueSource === undefined) return undefined;
395
+ const v = e.value;
396
+ const ok = typeof v === 'string' ? /^['"]/.test(e.valueSource)
397
+ : typeof v === 'number' ? Number.isFinite(v)
398
+ : typeof v === 'boolean';
399
+ if (!ok || (values.length > 0 && typeof v !== typeof values[0].value)) return undefined;
400
+ values.push({value: v as string | number | boolean, source: e.valueSource});
401
+ }
402
+ const repeats = new Set(values.map(v => v.value)).size !== values.length;
403
+ const order = values.map(v => v.value).sort();
404
+ const sorted: string[] = [];
405
+ const pool = [...values];
406
+ for (const value of order) {
407
+ sorted.push(pool.splice(pool.findIndex(v => v.value === value), 1)[0].source);
408
+ }
409
+ return {sorted, repeats};
410
+ }
@@ -0,0 +1,190 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ *
4
+ * Moderne Proprietary. Only for use by Moderne customers under the terms of a commercial contract.
5
+ */
6
+
7
+ import {Cursor, ExecutionContext, Recipe, TreeVisitor} from "@openrewrite/rewrite";
8
+ import {J, isFieldAccess, isMethodInvocation} from "@openrewrite/rewrite/java";
9
+ import {JS} from "@openrewrite/rewrite/javascript";
10
+ import {
11
+ JasmineToVitestVisitor,
12
+ Piece,
13
+ StatementResult,
14
+ args,
15
+ isGlobalCall,
16
+ isNamed,
17
+ isStringLiteral,
18
+ isTypePosition,
19
+ jasmineMethodName,
20
+ replaceWith,
21
+ select,
22
+ todoText
23
+ } from "./support";
24
+ import {commentedOut} from "./migrate-jasmine-matchers";
25
+
26
+ /**
27
+ * @see https://github.com/angular/angular-cli/blob/main/packages/schematics/angular/refactor/jasmine-vitest/transformers/jasmine-misc.ts
28
+ */
29
+ export class MigrateJasmineMiscToVitest extends Recipe {
30
+ readonly name = "org.openrewrite.angular.migration.migrate-jasmine-misc-to-vitest";
31
+ readonly displayName = "Migrate Jasmine's clock, `fail` and configuration to Vitest";
32
+ readonly description = "Rewrites `jasmine.clock()` to Vitest's fake timers (`install` to `vi.useFakeTimers()`, " +
33
+ "`tick` to `vi.advanceTimersByTime`, `uninstall` to `vi.useRealTimers()`, `mockDate` to `vi.setSystemTime`), " +
34
+ "`fail(...)` to `expect.fail(...)`, and `jasmine.DEFAULT_TIMEOUT_INTERVAL = n` to `vi.setConfig({ testTimeout: n })`. " +
35
+ "Jasmine APIs Vitest has no equivalent for, such as `jasmine.addMatchers` or `jasmine.clock().autoTick()`, and any " +
36
+ "other `jasmine.*` member, are left with a `TODO: vitest-migration` comment, as the Angular CLI's " +
37
+ "`refactor-jasmine-vitest` schematic does.";
38
+
39
+ async editor(): Promise<TreeVisitor<any, ExecutionContext>> {
40
+ return new MiscVisitor();
41
+ }
42
+ }
43
+
44
+ const CLOCK = new Map<string, string>([
45
+ ['install', 'useFakeTimers'],
46
+ ['tick', 'advanceTimersByTime'],
47
+ ['uninstall', 'useRealTimers'],
48
+ ['mockDate', 'setSystemTime'],
49
+ ]);
50
+
51
+ const UNSUPPORTED_GLOBALS = new Map<string, string>([
52
+ ['setSpecProperty', 'Unsupported global function `setSpecProperty` found. This function is used for custom reporters in Jasmine ' +
53
+ 'and has no direct equivalent in Vitest.'],
54
+ ['setSuiteProperty', 'Unsupported global function `setSuiteProperty` found. This function is used for custom reporters in Jasmine ' +
55
+ 'and has no direct equivalent in Vitest.'],
56
+ ['throwUnless', 'Unsupported global function `throwUnless` found. Please migrate manually to a direct assertion.'],
57
+ ['throwUnlessAsync', 'Unsupported global function `throwUnlessAsync` found. Please migrate manually to a direct assertion.'],
58
+ ['getSpecProperty', 'Unsupported global function `getSpecProperty` found. Please migrate manually.'],
59
+ ]);
60
+
61
+ const UNSUPPORTED_JASMINE_CALLS = new Map<string, [string, string?]>([
62
+ ['addMatchers', ['jasmine.addMatchers is not supported. Please manually migrate to expect.extend().',
63
+ 'https://vitest.dev/api/expect.html#expect-extend']],
64
+ ['addAsyncMatchers', ['jasmine.addAsyncMatchers is not supported. Please manually migrate to expect.extend().',
65
+ 'https://vitest.dev/api/expect.html#expect-extend']],
66
+ ['addCustomEqualityTester', ['jasmine.addCustomEqualityTester is not supported. Please manually migrate to expect.addEqualityTesters().',
67
+ 'https://vitest.dev/api/expect.html#expect-addequalitytesters']],
68
+ ['addCustomObjectFormatter', ['jasmine.addCustomObjectFormatter is not supported. May be possible to migrate to expect.addSnapshotSerializer().',
69
+ 'https://vitest.dev/api/expect.html#expect-addsnapshotserializer']],
70
+ ['mapContaining', ['jasmine.mapContaining is not supported. Vitest does not have a built-in matcher for Maps.' +
71
+ ' Please manually assert the contents of the Map.']],
72
+ ['setContaining', ['jasmine.setContaining is not supported. Vitest does not have a built-in matcher for Sets.' +
73
+ ' Please manually assert the contents of the Set.']],
74
+ ['addSpyStrategy', ['jasmine.addSpyStrategy is not supported. Please manually migrate to spy.mockImplementation().',
75
+ 'https://vitest.dev/api/mock.html#mockimplementation']],
76
+ ]);
77
+
78
+ /** The `jasmine.*` members some recipe of this migration handles; the rest get a TODO. */
79
+ const HANDLED_JASMINE_PROPERTIES = new Set([
80
+ 'createSpy', 'createSpyObj', 'spyOnAllFunctions', 'addSpyStrategy',
81
+ 'clock',
82
+ 'any', 'anything', 'stringMatching', 'objectContaining', 'arrayContaining', 'arrayWithExactContents',
83
+ 'truthy', 'falsy', 'empty', 'notEmpty', 'mapContaining', 'setContaining',
84
+ 'DEFAULT_TIMEOUT_INTERVAL', 'MAX_PRETTY_PRINT_ARRAY_LENGTH', 'MAX_PRETTY_PRINT_DEPTH', 'MAX_PRETTY_PRINT_CHARS',
85
+ 'addMatchers', 'addAsyncMatchers', 'addCustomEqualityTester', 'addCustomObjectFormatter',
86
+ ]);
87
+
88
+ class MiscVisitor extends JasmineToVitestVisitor {
89
+ protected override async visitMethodInvocation(method: J.MethodInvocation, p: ExecutionContext): Promise<J | undefined> {
90
+ const visited = await super.visitMethodInvocation(method, p);
91
+ if (!visited || !isMethodInvocation(visited)) return visited;
92
+ const m = visited;
93
+ const result = (await this.fail(m)) ?? (await this.timerMocks(m));
94
+ if (result) return result;
95
+ const global = !m.select ? UNSUPPORTED_GLOBALS.get(m.name.simpleName) : undefined;
96
+ if (global) {
97
+ this.todo(m, global);
98
+ return m;
99
+ }
100
+ const jasmineName = jasmineMethodName(m);
101
+ if (jasmineName) {
102
+ const unsupported = UNSUPPORTED_JASMINE_CALLS.get(jasmineName);
103
+ if (unsupported) {
104
+ this.todo(m, unsupported[0], unsupported[1]);
105
+ } else if (!HANDLED_JASMINE_PROPERTIES.has(jasmineName)) {
106
+ this.unknownProperty(m, jasmineName);
107
+ }
108
+ }
109
+ return m;
110
+ }
111
+
112
+ protected override async visitFieldAccess(fieldAccess: J.FieldAccess, p: ExecutionContext): Promise<J | undefined> {
113
+ const inType = isTypePosition(this.cursor);
114
+ const visited = await super.visitFieldAccess(fieldAccess, p);
115
+ if (!visited || !isFieldAccess(visited) || inType) return visited;
116
+ const name = visited.name.element.simpleName;
117
+ if (isNamed(visited.target, 'jasmine') && !HANDLED_JASMINE_PROPERTIES.has(name)) {
118
+ this.unknownProperty(visited, name);
119
+ }
120
+ return visited;
121
+ }
122
+
123
+ private unknownProperty(node: J, name: string): void {
124
+ this.todo(node, `Unsupported jasmine property "${name}" found. Please migrate this manually.`);
125
+ }
126
+
127
+ /** `fail(message)` to `expect.fail(message)`. */
128
+ private async fail(m: J.MethodInvocation): Promise<J | undefined> {
129
+ if (!isGlobalCall(m, 'fail')) return undefined;
130
+ const arg = args(m)[0];
131
+ let replacement: Piece[] = arg ? [arg] : [];
132
+ let nonString = false;
133
+ if (arg) {
134
+ if (arg.kind === J.Kind.NewClass) {
135
+ const first = args(arg as unknown as J.MethodInvocation)[0];
136
+ replacement = first ? [first] : [];
137
+ } else if (!isStringLiteral(arg) && arg.kind !== JS.Kind.TemplateExpression) {
138
+ replacement = ['String(', arg, ')'];
139
+ nonString = true;
140
+ }
141
+ }
142
+ const result = await replaceWith(m, this.cursor, 'expect.fail(', ...replacement, ')');
143
+ if (nonString) {
144
+ this.todo(result, 'expect.fail() only accepts a string message. ' +
145
+ 'Verify that converting this argument with String() produces the expected failure output.',
146
+ 'https://vitest.dev/api/expect.html#expect-fail');
147
+ }
148
+ return result;
149
+ }
150
+
151
+ /** `jasmine.clock().install()` and its siblings, to Vitest's fake timers. */
152
+ private async timerMocks(m: J.MethodInvocation): Promise<J | undefined> {
153
+ if (jasmineMethodName(select(m)) !== 'clock') return undefined;
154
+ const name = m.name.simpleName;
155
+ if (name === 'autoTick') {
156
+ this.todo(m, 'Vitest does not have a direct equivalent for jasmine.clock().autoTick(). Please migrate this manually.',
157
+ 'https://vitest.dev/api/vi.html#fake-timers');
158
+ return m;
159
+ }
160
+ if (name === 'withMock') {
161
+ this.todo(m, 'Vitest does not have a direct equivalent for jasmine.clock().withMock().' +
162
+ ' Please migrate this manually via vi.useFakeTimers() and vi.useRealTimers().',
163
+ 'https://vitest.dev/api/vi.html#vi-usefaketimers');
164
+ return m;
165
+ }
166
+ const vitest = CLOCK.get(name);
167
+ if (!vitest) return undefined;
168
+ let newArgs: Piece[] = [args(m)];
169
+ if (vitest === 'useFakeTimers') newArgs = [];
170
+ if (vitest === 'setSystemTime' && args(m).length === 0) newArgs = ['new Date()'];
171
+ return replaceWith(m, this.cursor, `vi.${vitest}(`, ...newArgs, ')');
172
+ }
173
+
174
+ protected override async visitBlockStatement(statement: J, cursor: Cursor): Promise<StatementResult | undefined> {
175
+ if (statement.kind !== J.Kind.Assignment) return undefined;
176
+ const assignment = statement as J.Assignment;
177
+ const variable = assignment.variable;
178
+ if (!isFieldAccess(variable) || !isNamed(variable.target, 'jasmine')) return undefined;
179
+ const member = variable.name.element.simpleName;
180
+ switch (member) {
181
+ case 'DEFAULT_TIMEOUT_INTERVAL':
182
+ return {replace: [await replaceWith(statement, cursor, 'vi.setConfig({ testTimeout: ', assignment.assignment.element, ' })')]};
183
+ case 'MAX_PRETTY_PRINT_ARRAY_LENGTH':
184
+ case 'MAX_PRETTY_PRINT_DEPTH':
185
+ case 'MAX_PRETTY_PRINT_CHARS':
186
+ return {removeLeaving: [todoText(`jasmine.${member} is not supported.`), ...await commentedOut(statement, cursor)]};
187
+ }
188
+ return undefined;
189
+ }
190
+ }