forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjasmine-matcher.ts
More file actions
672 lines (566 loc) · 19.4 KB
/
jasmine-matcher.ts
File metadata and controls
672 lines (566 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @fileoverview This file contains transformers that migrate Jasmine matchers to their
* Vitest counterparts. It handles a wide range of matchers, including syntactic sugar
* (e.g., `toBeTrue`), asymmetric matchers (e.g., `jasmine.any`), async promise matchers
* (`expectAsync`), and complex matchers that require restructuring, such as
* `toHaveBeenCalledOnceWith` and `arrayWithExactContents`.
*/
import ts from '../../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
import {
addVitestValueImport,
createExpectCallExpression,
createPropertyAccess,
} from '../utils/ast-helpers';
import { getJasmineMethodName, isJasmineCallExpression } from '../utils/ast-validation';
import { addTodoComment } from '../utils/comment-helpers';
import { RefactorContext } from '../utils/refactor-context';
const SUGAR_MATCHER_CHANGES = new Map<string, { newName: string; newArgs?: ts.Expression[] }>([
['toBeTrue', { newName: 'toBe', newArgs: [ts.factory.createTrue()] }],
['toBeFalse', { newName: 'toBe', newArgs: [ts.factory.createFalse()] }],
['toBePositiveInfinity', { newName: 'toBe', newArgs: [ts.factory.createIdentifier('Infinity')] }],
[
'toBeNegativeInfinity',
{
newName: 'toBe',
newArgs: [
ts.factory.createPrefixUnaryExpression(
ts.SyntaxKind.MinusToken,
ts.factory.createIdentifier('Infinity'),
),
],
},
],
['toHaveSize', { newName: 'toHaveLength' }],
]);
export function transformSyntacticSugarMatchers(
node: ts.Node,
{ sourceFile, reporter }: RefactorContext,
): ts.Node {
if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression)) {
return node;
}
const pae = node.expression;
const matcherName = pae.name.text;
if (matcherName === 'toHaveSpyInteractions') {
const category = 'toHaveSpyInteractions';
reporter.recordTodo(category, sourceFile, node);
addTodoComment(node, category);
return node;
}
if (matcherName === 'toThrowMatching') {
const category = 'toThrowMatching';
reporter.recordTodo(category, sourceFile, node);
addTodoComment(node, category, { name: matcherName });
return node;
}
const mapping = SUGAR_MATCHER_CHANGES.get(matcherName);
if (mapping) {
reporter.reportTransformation(
sourceFile,
node,
`Transformed matcher ".${matcherName}()" to ".${mapping.newName}()".`,
);
const newExpression = createPropertyAccess(pae.expression, mapping.newName);
const newArgs = mapping.newArgs ?? [...node.arguments];
return ts.factory.updateCallExpression(node, newExpression, node.typeArguments, newArgs);
}
return node;
}
const ASYMMETRIC_MATCHER_NAMES: ReadonlyArray<string> = [
'anything',
'any',
'stringMatching',
'objectContaining',
'arrayContaining',
'stringContaining',
];
export function transformAsymmetricMatchers(
node: ts.Node,
{ sourceFile, reporter, pendingVitestValueImports }: RefactorContext,
): ts.Node {
if (
ts.isPropertyAccessExpression(node) &&
ts.isIdentifier(node.expression) &&
node.expression.text === 'jasmine'
) {
const matcherName = node.name.text;
if (ASYMMETRIC_MATCHER_NAMES.includes(matcherName)) {
addVitestValueImport(pendingVitestValueImports, 'expect');
reporter.reportTransformation(
sourceFile,
node,
`Transformed asymmetric matcher \`jasmine.${matcherName}\` to \`expect.${matcherName}\`.`,
);
return createPropertyAccess('expect', node.name);
}
}
return node;
}
export function transformToHaveBeenCalledBefore(
node: ts.Node,
{ sourceFile, reporter }: RefactorContext,
): ts.Node {
if (
!ts.isCallExpression(node) ||
!ts.isPropertyAccessExpression(node.expression) ||
node.arguments.length !== 1
) {
return node;
}
const pae = node.expression;
const matcherName = pae.name.text;
let isNegated = false;
let expectExpression = pae.expression;
if (ts.isPropertyAccessExpression(expectExpression) && expectExpression.name.text === 'not') {
isNegated = true;
expectExpression = expectExpression.expression;
}
if (!ts.isCallExpression(expectExpression) || matcherName !== 'toHaveBeenCalledBefore') {
return node;
}
reporter.reportTransformation(
sourceFile,
node,
'Transformed `toHaveBeenCalledBefore` to a Vitest-compatible spy invocation order comparison.',
);
const [spyB] = node.arguments;
const [spyA] = expectExpression.arguments;
const createInvocationOrderAccess = (spyIdentifier: ts.Expression) => {
const mockedSpy = ts.factory.createCallExpression(
createPropertyAccess('vi', 'mocked'),
undefined,
[spyIdentifier],
);
const mockProperty = createPropertyAccess(mockedSpy, 'mock');
return createPropertyAccess(mockProperty, 'invocationCallOrder');
};
const createMinCall = (spyIdentifier: ts.Expression) => {
return ts.factory.createCallExpression(createPropertyAccess('Math', 'min'), undefined, [
ts.factory.createSpreadElement(createInvocationOrderAccess(spyIdentifier)),
]);
};
const newExpect = createExpectCallExpression([createMinCall(spyA)]);
const newMatcherName = isNegated ? 'toBeGreaterThanOrEqual' : 'toBeLessThan';
return ts.factory.createCallExpression(
createPropertyAccess(newExpect, newMatcherName),
undefined,
[createMinCall(spyB)],
);
}
export function transformToHaveClass(
node: ts.Node,
{ sourceFile, reporter }: RefactorContext,
): ts.Node {
if (
!ts.isCallExpression(node) ||
!ts.isPropertyAccessExpression(node.expression) ||
node.arguments.length !== 1
) {
return node;
}
const pae = node.expression;
const matcherName = pae.name.text;
let isNegated = false;
let expectExpression = pae.expression;
if (ts.isPropertyAccessExpression(expectExpression) && expectExpression.name.text === 'not') {
isNegated = true;
expectExpression = expectExpression.expression;
}
if (matcherName !== 'toHaveClass' || !ts.isCallExpression(expectExpression)) {
return node;
}
reporter.reportTransformation(
sourceFile,
node,
'Transformed `.toHaveClass()` to a `classList.contains()` check.',
);
const [className] = node.arguments;
const newExpectArgs: ts.Expression[] = [];
const [element] = expectExpression.arguments;
const classListContains = ts.factory.createCallExpression(
createPropertyAccess(createPropertyAccess(element, 'classList'), 'contains'),
undefined,
[className],
);
newExpectArgs.push(classListContains);
// Pass the context message from withContext to the new expect call
if (expectExpression.arguments.length > 1) {
newExpectArgs.push(expectExpression.arguments[1]);
}
const newExpect = createExpectCallExpression(newExpectArgs);
const newMatcher = isNegated ? ts.factory.createFalse() : ts.factory.createTrue();
return ts.factory.createCallExpression(createPropertyAccess(newExpect, 'toBe'), undefined, [
newMatcher,
]);
}
const ASYNC_MATCHER_CHANGES = new Map<
string,
{
base: 'resolves' | 'rejects';
matcher: string;
not?: boolean;
keepArgs?: boolean;
}
>([
['toBeResolved', { base: 'resolves', matcher: 'toThrow', not: true, keepArgs: false }],
['toBeResolvedTo', { base: 'resolves', matcher: 'toEqual', keepArgs: true }],
['toBeRejected', { base: 'rejects', matcher: 'toThrow', keepArgs: false }],
['toBeRejectedWith', { base: 'rejects', matcher: 'toEqual', keepArgs: true }],
['toBeRejectedWithError', { base: 'rejects', matcher: 'toThrowError', keepArgs: true }],
]);
export function transformExpectAsync(
node: ts.Node,
{ sourceFile, reporter }: RefactorContext,
): ts.Node {
if (
!ts.isCallExpression(node) ||
!ts.isPropertyAccessExpression(node.expression) ||
!ts.isCallExpression(node.expression.expression)
) {
return node;
}
const matcherCall = node;
const matcherPae = node.expression;
const expectCall = node.expression.expression;
if (!ts.isIdentifier(expectCall.expression) || expectCall.expression.text !== 'expectAsync') {
return node;
}
const matcherName = ts.isIdentifier(matcherPae.name) ? matcherPae.name.text : undefined;
const mapping = matcherName ? ASYNC_MATCHER_CHANGES.get(matcherName) : undefined;
if (mapping) {
reporter.reportTransformation(
sourceFile,
node,
`Transformed \`expectAsync(...).${matcherName}\` to \`expect(...).${mapping.base}.${mapping.matcher}\`.`,
);
const newExpectCall = createExpectCallExpression([expectCall.arguments[0]]);
let newMatcherChain: ts.Expression = createPropertyAccess(newExpectCall, mapping.base);
if (mapping.not) {
newMatcherChain = createPropertyAccess(newMatcherChain, 'not');
}
newMatcherChain = createPropertyAccess(newMatcherChain, mapping.matcher);
const newMatcherArgs = mapping.keepArgs ? [...matcherCall.arguments] : [];
return ts.factory.createCallExpression(newMatcherChain, undefined, newMatcherArgs);
}
if (matcherName) {
if (matcherName === 'toBePending') {
const category = 'toBePending';
reporter.recordTodo(category, sourceFile, node);
addTodoComment(node, category);
} else {
const category = 'unsupported-expect-async-matcher';
reporter.recordTodo(category, sourceFile, node);
addTodoComment(node, category, { name: matcherName });
}
}
return node;
}
export function transformComplexMatchers(
node: ts.Node,
{ sourceFile, reporter }: RefactorContext,
): ts.Node {
if (
!ts.isCallExpression(node) ||
!ts.isPropertyAccessExpression(node.expression) ||
node.expression.name.text !== 'toEqual' ||
node.arguments.length !== 1
) {
return node;
}
const argument = node.arguments[0];
const jasmineMatcherName = getJasmineMethodName(argument);
if (!jasmineMatcherName) {
return node;
}
const expectCall = node.expression.expression;
let newMatcherName: string | undefined;
let newArgs: ts.Expression[] | undefined;
let negate = false;
switch (jasmineMatcherName) {
case 'truthy':
newMatcherName = 'toBeTruthy';
break;
case 'falsy':
newMatcherName = 'toBeFalsy';
break;
case 'empty':
newMatcherName = 'toHaveLength';
newArgs = [ts.factory.createNumericLiteral(0)];
break;
case 'notEmpty':
newMatcherName = 'toHaveLength';
newArgs = [ts.factory.createNumericLiteral(0)];
negate = true;
break;
case 'is':
newMatcherName = 'toBe';
if (ts.isCallExpression(argument)) {
newArgs = [...argument.arguments];
}
break;
}
if (newMatcherName) {
reporter.reportTransformation(
sourceFile,
node,
`Transformed \`.toEqual(jasmine.${jasmineMatcherName}())\` to \`.${newMatcherName}()\`.`,
);
let expectExpression = expectCall;
// Handle cases like `expect(...).not.toEqual(jasmine.notEmpty())`
if (ts.isPropertyAccessExpression(expectCall) && expectCall.name.text === 'not') {
// The original expression was negated, so flip the negate flag
negate = !negate;
// Use the expression before the `.not`
expectExpression = expectCall.expression;
}
if (negate) {
expectExpression = createPropertyAccess(expectExpression, 'not');
}
const newExpression = createPropertyAccess(expectExpression, newMatcherName);
return ts.factory.createCallExpression(newExpression, undefined, newArgs ?? []);
}
return node;
}
export function transformArrayWithExactContents(
node: ts.Node,
{ sourceFile, reporter }: RefactorContext,
): ts.Node | readonly ts.Node[] {
if (
!ts.isExpressionStatement(node) ||
!ts.isCallExpression(node.expression) ||
!ts.isPropertyAccessExpression(node.expression.expression) ||
node.expression.expression.name.text !== 'toEqual' ||
node.expression.arguments.length !== 1
) {
return node;
}
const argument = node.expression.arguments[0];
if (
!isJasmineCallExpression(argument, 'arrayWithExactContents') ||
argument.arguments.length !== 1
) {
return node;
}
if (!ts.isArrayLiteralExpression(argument.arguments[0])) {
const category = 'arrayWithExactContents-dynamic-variable';
reporter.recordTodo(category, sourceFile, node);
addTodoComment(node, category);
return node;
}
reporter.reportTransformation(
sourceFile,
node,
'Transformed `jasmine.arrayWithExactContents()` to `.toHaveLength()` and `.toEqual(expect.arrayContaining())`.',
);
const expectCall = node.expression.expression.expression;
const arrayLiteral = argument.arguments[0];
const lengthCall = ts.factory.createCallExpression(
createPropertyAccess(expectCall, 'toHaveLength'),
undefined,
[ts.factory.createNumericLiteral(arrayLiteral.elements.length)],
);
const containingCall = ts.factory.createCallExpression(
createPropertyAccess(expectCall, 'toEqual'),
undefined,
[
ts.factory.createCallExpression(
createPropertyAccess('expect', 'arrayContaining'),
undefined,
[arrayLiteral],
),
],
);
const lengthStmt = ts.factory.createExpressionStatement(lengthCall);
const containingStmt = ts.factory.createExpressionStatement(containingCall);
const category = 'arrayWithExactContents-check';
reporter.recordTodo(category, sourceFile, node);
addTodoComment(lengthStmt, category);
return [lengthStmt, containingStmt];
}
export function transformCalledOnceWith(
node: ts.Node,
{ sourceFile, reporter }: RefactorContext,
): ts.Node | readonly ts.Node[] {
if (!ts.isExpressionStatement(node)) {
return node;
}
const call = node.expression;
if (
!ts.isCallExpression(call) ||
!ts.isPropertyAccessExpression(call.expression) ||
call.expression.name.text !== 'toHaveBeenCalledOnceWith'
) {
return node;
}
reporter.reportTransformation(
sourceFile,
node,
'Transformed `.toHaveBeenCalledOnceWith()` to `.toHaveBeenCalledTimes(1)` and `.toHaveBeenCalledWith()`.',
);
const expectCall = call.expression.expression;
const args = call.arguments;
const timesCall = ts.factory.createCallExpression(
createPropertyAccess(expectCall, 'toHaveBeenCalledTimes'),
undefined,
[ts.factory.createNumericLiteral(1)],
);
const withCall = ts.factory.createCallExpression(
createPropertyAccess(expectCall, 'toHaveBeenCalledWith'),
undefined,
args,
);
return [
ts.factory.createExpressionStatement(timesCall),
ts.factory.createExpressionStatement(withCall),
];
}
export function transformWithContext(
node: ts.Node,
{ sourceFile, reporter }: RefactorContext,
): ts.Node {
if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression)) {
return node;
}
// Traverse the chain of property access expressions to find the .withContext() call
let currentExpression: ts.Expression = node.expression;
const propertyChain: ts.Identifier[] = [];
while (ts.isPropertyAccessExpression(currentExpression)) {
if (!ts.isIdentifier(currentExpression.name)) {
// Break if we encounter a private identifier or something else unexpected
return node;
}
propertyChain.push(currentExpression.name);
currentExpression = currentExpression.expression;
}
const withContextCall = currentExpression;
// Check if we found a .withContext() call
if (
!ts.isCallExpression(withContextCall) ||
!ts.isPropertyAccessExpression(withContextCall.expression) ||
!ts.isIdentifier(withContextCall.expression.name) ||
withContextCall.expression.name.text !== 'withContext'
) {
return node;
}
reporter.reportTransformation(
sourceFile,
withContextCall,
'Transformed `.withContext()` to the `expect(..., message)` syntax.',
);
const expectCall = withContextCall.expression.expression;
if (
!ts.isCallExpression(expectCall) ||
!ts.isIdentifier(expectCall.expression) ||
expectCall.expression.text !== 'expect'
) {
return node;
}
const contextMessage = withContextCall.arguments[0];
if (!contextMessage) {
// No message provided, so unwrap the .withContext() call.
let newChain: ts.Expression = expectCall;
for (let i = propertyChain.length - 1; i >= 0; i--) {
newChain = ts.factory.createPropertyAccessExpression(newChain, propertyChain[i]);
}
return ts.factory.updateCallExpression(node, newChain, node.typeArguments, node.arguments);
}
const newExpectArgs = [...expectCall.arguments, contextMessage];
const newExpectCall = ts.factory.updateCallExpression(
expectCall,
expectCall.expression,
expectCall.typeArguments,
newExpectArgs,
);
// Rebuild the property access chain
let newExpression: ts.Expression = newExpectCall;
for (let i = propertyChain.length - 1; i >= 0; i--) {
newExpression = ts.factory.createPropertyAccessExpression(newExpression, propertyChain[i]);
}
return ts.factory.updateCallExpression(node, newExpression, node.typeArguments, node.arguments);
}
export function transformExpectNothing(
node: ts.Node,
{ sourceFile, reporter }: RefactorContext,
): ts.Node {
if (!ts.isExpressionStatement(node)) {
return node;
}
const call = node.expression;
if (
!ts.isCallExpression(call) ||
!ts.isPropertyAccessExpression(call.expression) ||
!ts.isIdentifier(call.expression.name) ||
call.expression.name.text !== 'nothing'
) {
return node;
}
const expectCall = call.expression.expression;
if (
!ts.isCallExpression(expectCall) ||
!ts.isIdentifier(expectCall.expression) ||
expectCall.expression.text !== 'expect' ||
expectCall.arguments.length > 0
) {
return node;
}
// The statement is `expect().nothing()`, which can be removed.
const replacement = ts.factory.createEmptyStatement();
const originalText = node.getFullText().trim();
reporter.reportTransformation(sourceFile, node, 'Removed `expect().nothing()` statement.');
const category = 'expect-nothing';
reporter.recordTodo(category, sourceFile, node);
addTodoComment(replacement, category);
ts.addSyntheticLeadingComment(
replacement,
ts.SyntaxKind.SingleLineCommentTrivia,
` ${originalText}`,
true,
);
return replacement;
}
export function transformToBeNullish(
node: ts.Node,
{ sourceFile, reporter }: RefactorContext,
): ts.Node {
if (
!ts.isCallExpression(node) ||
!ts.isPropertyAccessExpression(node.expression) ||
node.arguments.length !== 0
) {
return node;
}
const pae = node.expression;
const matcherName = pae.name.text;
let isNegated = false;
let expectExpression = pae.expression;
if (ts.isPropertyAccessExpression(expectExpression) && expectExpression.name.text === 'not') {
isNegated = true;
expectExpression = expectExpression.expression;
}
if (matcherName !== 'toBeNullish' || !ts.isCallExpression(expectExpression)) {
return node;
}
reporter.reportTransformation(
sourceFile,
node,
'Transformed `.toBeNullish()` to a `element == null` check.',
);
const element = expectExpression.arguments[0];
const nullCheckExpression = ts.factory.createBinaryExpression(
element,
ts.SyntaxKind.EqualsEqualsToken,
ts.factory.createNull(),
);
const newExpect = createExpectCallExpression([nullCheckExpression]);
const newMatcher = isNegated ? ts.factory.createFalse() : ts.factory.createTrue();
return ts.factory.createCallExpression(createPropertyAccess(newExpect, 'toBe'), undefined, [
newMatcher,
]);
}