Primeiro commit do projeto Angular
This commit is contained in:
Generated
Vendored
+18
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* @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 convert Jasmine lifecycle functions
|
||||
* and test setup/teardown patterns to their Vitest equivalents. This includes handling
|
||||
* focused/skipped tests (fdescribe, fit, xdescribe, xit), pending tests, and asynchronous
|
||||
* operations that use the `done` callback.
|
||||
*/
|
||||
import ts from '../../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
|
||||
import { RefactorContext } from '../utils/refactor-context';
|
||||
export declare function transformFocusedAndSkippedTests(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
|
||||
export declare function transformPending(node: ts.Node, { sourceFile, reporter, tsContext }: RefactorContext): ts.Node;
|
||||
export declare function transformDoneCallback(node: ts.Node, refactorCtx: RefactorContext): ts.Node;
|
||||
Generated
Vendored
+276
@@ -0,0 +1,276 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.transformFocusedAndSkippedTests = transformFocusedAndSkippedTests;
|
||||
exports.transformPending = transformPending;
|
||||
exports.transformDoneCallback = transformDoneCallback;
|
||||
/**
|
||||
* @fileoverview This file contains transformers that convert Jasmine lifecycle functions
|
||||
* and test setup/teardown patterns to their Vitest equivalents. This includes handling
|
||||
* focused/skipped tests (fdescribe, fit, xdescribe, xit), pending tests, and asynchronous
|
||||
* operations that use the `done` callback.
|
||||
*/
|
||||
const typescript_1 = __importDefault(require("../../../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
|
||||
const ast_helpers_1 = require("../utils/ast-helpers");
|
||||
const comment_helpers_1 = require("../utils/comment-helpers");
|
||||
const FOCUSED_SKIPPED_RENAMES = new Map([
|
||||
['fdescribe', { newBase: 'describe', newName: 'only' }],
|
||||
['fit', { newBase: 'it', newName: 'only' }],
|
||||
['xdescribe', { newBase: 'describe', newName: 'skip' }],
|
||||
['xit', { newBase: 'it', newName: 'skip' }],
|
||||
]);
|
||||
function transformFocusedAndSkippedTests(node, { sourceFile, reporter }) {
|
||||
if (!typescript_1.default.isCallExpression(node) || !typescript_1.default.isIdentifier(node.expression)) {
|
||||
return node;
|
||||
}
|
||||
const oldName = node.expression.text;
|
||||
const rename = FOCUSED_SKIPPED_RENAMES.get(oldName);
|
||||
if (rename) {
|
||||
reporter.reportTransformation(sourceFile, node, `Transformed \`${oldName}\` to \`${rename.newBase}.${rename.newName}\`.`);
|
||||
const newPropAccess = (0, ast_helpers_1.createPropertyAccess)(rename.newBase, rename.newName);
|
||||
return typescript_1.default.factory.updateCallExpression(node, newPropAccess, node.typeArguments, node.arguments);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
function transformPending(node, { sourceFile, reporter, tsContext }) {
|
||||
if (!typescript_1.default.isCallExpression(node) ||
|
||||
!typescript_1.default.isIdentifier(node.expression) ||
|
||||
node.expression.text !== 'it') {
|
||||
return node;
|
||||
}
|
||||
const testFn = node.arguments[1];
|
||||
if (!testFn || (!typescript_1.default.isArrowFunction(testFn) && !typescript_1.default.isFunctionExpression(testFn))) {
|
||||
return node;
|
||||
}
|
||||
let hasPending = false;
|
||||
const bodyTransformVisitor = (bodyNode) => {
|
||||
if (typescript_1.default.isExpressionStatement(bodyNode) &&
|
||||
typescript_1.default.isCallExpression(bodyNode.expression) &&
|
||||
typescript_1.default.isIdentifier(bodyNode.expression.expression) &&
|
||||
bodyNode.expression.expression.text === 'pending') {
|
||||
hasPending = true;
|
||||
const replacement = typescript_1.default.factory.createEmptyStatement();
|
||||
const originalText = bodyNode.getFullText().trim();
|
||||
reporter.reportTransformation(sourceFile, bodyNode, 'Converted `pending()` to a skipped test (`it.skip`).');
|
||||
const category = 'pending';
|
||||
reporter.recordTodo(category, sourceFile, bodyNode);
|
||||
(0, comment_helpers_1.addTodoComment)(replacement, category);
|
||||
typescript_1.default.addSyntheticLeadingComment(replacement, typescript_1.default.SyntaxKind.SingleLineCommentTrivia, ` ${originalText}`, true);
|
||||
return replacement;
|
||||
}
|
||||
return typescript_1.default.visitEachChild(bodyNode, bodyTransformVisitor, tsContext);
|
||||
};
|
||||
const newBody = typescript_1.default.visitNode(testFn.body, bodyTransformVisitor);
|
||||
if (!hasPending) {
|
||||
return node;
|
||||
}
|
||||
const newExpression = (0, ast_helpers_1.createPropertyAccess)(node.expression, 'skip');
|
||||
const newTestFn = typescript_1.default.isArrowFunction(testFn)
|
||||
? typescript_1.default.factory.updateArrowFunction(testFn, testFn.modifiers, testFn.typeParameters, testFn.parameters, testFn.type, testFn.equalsGreaterThanToken, newBody ?? typescript_1.default.factory.createBlock([]))
|
||||
: typescript_1.default.factory.updateFunctionExpression(testFn, testFn.modifiers, testFn.asteriskToken, testFn.name, testFn.typeParameters, testFn.parameters, testFn.type, newBody ?? typescript_1.default.factory.createBlock([]));
|
||||
const newArgs = [node.arguments[0], newTestFn, ...node.arguments.slice(2)];
|
||||
return typescript_1.default.factory.updateCallExpression(node, newExpression, node.typeArguments, newArgs);
|
||||
}
|
||||
function transformComplexDoneCallback(node, doneIdentifier, refactorCtx) {
|
||||
const { sourceFile, reporter } = refactorCtx;
|
||||
if (!typescript_1.default.isExpressionStatement(node) ||
|
||||
!typescript_1.default.isCallExpression(node.expression) ||
|
||||
!typescript_1.default.isPropertyAccessExpression(node.expression.expression)) {
|
||||
return node;
|
||||
}
|
||||
const call = node.expression;
|
||||
const pae = call.expression;
|
||||
if (!typescript_1.default.isPropertyAccessExpression(pae)) {
|
||||
return node;
|
||||
}
|
||||
if (pae.name.text !== 'then' || call.arguments.length !== 1) {
|
||||
return node;
|
||||
}
|
||||
const thenCallback = call.arguments[0];
|
||||
if (!typescript_1.default.isArrowFunction(thenCallback) && !typescript_1.default.isFunctionExpression(thenCallback)) {
|
||||
return node;
|
||||
}
|
||||
// Re-create the .then() call but with a modified callback that has `done()` removed.
|
||||
const thenCallbackBody = typescript_1.default.isBlock(thenCallback.body)
|
||||
? thenCallback.body
|
||||
: typescript_1.default.factory.createBlock([typescript_1.default.factory.createExpressionStatement(thenCallback.body)]);
|
||||
const newStatements = thenCallbackBody.statements.filter((stmt) => {
|
||||
return (!typescript_1.default.isExpressionStatement(stmt) ||
|
||||
!typescript_1.default.isCallExpression(stmt.expression) ||
|
||||
!typescript_1.default.isIdentifier(stmt.expression.expression) ||
|
||||
stmt.expression.expression.text !== doneIdentifier.text);
|
||||
});
|
||||
if (newStatements.length === thenCallbackBody.statements.length) {
|
||||
// No "done()" call was removed, so don't transform.
|
||||
return node;
|
||||
}
|
||||
reporter.reportTransformation(sourceFile, node, 'Transformed promise `.then()` with `done()` to `await`.');
|
||||
const newThenCallback = typescript_1.default.isArrowFunction(thenCallback)
|
||||
? typescript_1.default.factory.updateArrowFunction(thenCallback, thenCallback.modifiers, thenCallback.typeParameters, thenCallback.parameters, thenCallback.type, thenCallback.equalsGreaterThanToken, typescript_1.default.factory.updateBlock(thenCallbackBody, newStatements))
|
||||
: typescript_1.default.factory.updateFunctionExpression(thenCallback, thenCallback.modifiers, thenCallback.asteriskToken, thenCallback.name, thenCallback.typeParameters, thenCallback.parameters, thenCallback.type, typescript_1.default.factory.updateBlock(thenCallbackBody, newStatements));
|
||||
const newCall = typescript_1.default.factory.updateCallExpression(call, call.expression, call.typeArguments, [
|
||||
newThenCallback,
|
||||
]);
|
||||
return typescript_1.default.factory.createExpressionStatement(typescript_1.default.factory.createAwaitExpression(newCall));
|
||||
}
|
||||
function transformPromiseBasedDone(callExpr, doneIdentifier, refactorCtx) {
|
||||
const { sourceFile, reporter } = refactorCtx;
|
||||
if (typescript_1.default.isPropertyAccessExpression(callExpr.expression) &&
|
||||
(callExpr.expression.name.text === 'then' || callExpr.expression.name.text === 'catch')) {
|
||||
const promiseHandler = callExpr.arguments[0];
|
||||
if (promiseHandler) {
|
||||
let isDoneHandler = false;
|
||||
// promise.then(done)
|
||||
if (typescript_1.default.isIdentifier(promiseHandler) && promiseHandler.text === doneIdentifier.text) {
|
||||
isDoneHandler = true;
|
||||
}
|
||||
// promise.catch(done.fail)
|
||||
if (typescript_1.default.isPropertyAccessExpression(promiseHandler) &&
|
||||
typescript_1.default.isIdentifier(promiseHandler.expression) &&
|
||||
promiseHandler.expression.text === doneIdentifier.text &&
|
||||
promiseHandler.name.text === 'fail') {
|
||||
isDoneHandler = true;
|
||||
}
|
||||
// promise.then(() => done())
|
||||
if (typescript_1.default.isArrowFunction(promiseHandler) && !promiseHandler.parameters.length) {
|
||||
const body = promiseHandler.body;
|
||||
if (typescript_1.default.isCallExpression(body) &&
|
||||
typescript_1.default.isIdentifier(body.expression) &&
|
||||
body.expression.text === doneIdentifier.text) {
|
||||
isDoneHandler = true;
|
||||
}
|
||||
if (typescript_1.default.isBlock(body) && body.statements.length === 1) {
|
||||
const stmt = body.statements[0];
|
||||
if (typescript_1.default.isExpressionStatement(stmt) &&
|
||||
typescript_1.default.isCallExpression(stmt.expression) &&
|
||||
typescript_1.default.isIdentifier(stmt.expression.expression) &&
|
||||
stmt.expression.expression.text === doneIdentifier.text) {
|
||||
isDoneHandler = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isDoneHandler) {
|
||||
reporter.reportTransformation(sourceFile, callExpr, 'Transformed promise `.then(done)` to `await`.');
|
||||
return typescript_1.default.factory.createExpressionStatement(typescript_1.default.factory.createAwaitExpression(callExpr.expression.expression));
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
function countDoneUsages(node, doneIdentifier) {
|
||||
let count = 0;
|
||||
const visitor = (n) => {
|
||||
if (typescript_1.default.isIdentifier(n) && n.text === doneIdentifier.text) {
|
||||
count++;
|
||||
}
|
||||
typescript_1.default.forEachChild(n, visitor);
|
||||
};
|
||||
typescript_1.default.forEachChild(node, visitor);
|
||||
return count;
|
||||
}
|
||||
function transformDoneCallback(node, refactorCtx) {
|
||||
const { sourceFile, reporter, tsContext } = refactorCtx;
|
||||
if (!typescript_1.default.isCallExpression(node) ||
|
||||
!typescript_1.default.isIdentifier(node.expression) ||
|
||||
!['it', 'beforeEach', 'afterEach', 'beforeAll', 'afterAll'].includes(node.expression.text)) {
|
||||
return node;
|
||||
}
|
||||
const functionArg = node.arguments.find((arg) => typescript_1.default.isArrowFunction(arg) || typescript_1.default.isFunctionExpression(arg));
|
||||
if (!functionArg || (!typescript_1.default.isArrowFunction(functionArg) && !typescript_1.default.isFunctionExpression(functionArg))) {
|
||||
return node;
|
||||
}
|
||||
if (functionArg.parameters.length !== 1) {
|
||||
return node;
|
||||
}
|
||||
const doneParam = functionArg.parameters[0];
|
||||
if (!typescript_1.default.isIdentifier(doneParam.name)) {
|
||||
return node;
|
||||
}
|
||||
const doneIdentifier = doneParam.name;
|
||||
// Count total usages of 'done' in the body
|
||||
const totalUsages = countDoneUsages(functionArg.body, doneIdentifier);
|
||||
let handledUsages = 0;
|
||||
let doneWasUsed = false;
|
||||
const bodyVisitor = (bodyNode) => {
|
||||
const complexTransformed = transformComplexDoneCallback(bodyNode, doneIdentifier, refactorCtx);
|
||||
if (complexTransformed !== bodyNode) {
|
||||
doneWasUsed = true;
|
||||
handledUsages++; // complex transform handles one usage
|
||||
return complexTransformed;
|
||||
}
|
||||
if (typescript_1.default.isExpressionStatement(bodyNode) && typescript_1.default.isCallExpression(bodyNode.expression)) {
|
||||
const callExpr = bodyNode.expression;
|
||||
// Transform `done.fail('message')` to `throw new Error('message')`
|
||||
if (typescript_1.default.isPropertyAccessExpression(callExpr.expression) &&
|
||||
typescript_1.default.isIdentifier(callExpr.expression.expression) &&
|
||||
callExpr.expression.expression.text === doneIdentifier.text &&
|
||||
callExpr.expression.name.text === 'fail') {
|
||||
doneWasUsed = true;
|
||||
handledUsages++;
|
||||
reporter.reportTransformation(sourceFile, bodyNode, 'Transformed `done.fail()` to `throw new Error()`.');
|
||||
const errorArgs = callExpr.arguments.length > 0 ? [callExpr.arguments[0]] : [];
|
||||
return typescript_1.default.factory.createThrowStatement(typescript_1.default.factory.createNewExpression(typescript_1.default.factory.createIdentifier('Error'), undefined, errorArgs));
|
||||
}
|
||||
// Transform `promise.then(done)` or `promise.catch(done.fail)` to `await promise`
|
||||
const promiseTransformed = transformPromiseBasedDone(callExpr, doneIdentifier, refactorCtx);
|
||||
if (promiseTransformed) {
|
||||
doneWasUsed = true;
|
||||
handledUsages++;
|
||||
return promiseTransformed;
|
||||
}
|
||||
// Remove `done()`
|
||||
if (typescript_1.default.isIdentifier(callExpr.expression) &&
|
||||
callExpr.expression.text === doneIdentifier.text) {
|
||||
doneWasUsed = true;
|
||||
handledUsages++;
|
||||
return typescript_1.default.setTextRange(typescript_1.default.factory.createEmptyStatement(), callExpr.expression);
|
||||
}
|
||||
}
|
||||
return typescript_1.default.visitEachChild(bodyNode, bodyVisitor, tsContext);
|
||||
};
|
||||
const newBody = typescript_1.default.visitNode(functionArg.body, (node) => {
|
||||
if (typescript_1.default.isBlock(node)) {
|
||||
const newStatements = node.statements.flatMap((stmt) => bodyVisitor(stmt));
|
||||
return typescript_1.default.factory.updateBlock(node, newStatements.filter((s) => !!s));
|
||||
}
|
||||
return bodyVisitor(node);
|
||||
});
|
||||
// Safety check: if we found usages but didn't handle all of them, abort.
|
||||
if (handledUsages < totalUsages) {
|
||||
reporter.reportTransformation(sourceFile, node, `Found unhandled usage of \`${doneIdentifier.text}\` callback. Skipping transformation.`);
|
||||
const category = 'unhandled-done-usage';
|
||||
reporter.recordTodo(category, sourceFile, node);
|
||||
(0, comment_helpers_1.addTodoComment)(node, category);
|
||||
return node;
|
||||
}
|
||||
if (!doneWasUsed) {
|
||||
return node;
|
||||
}
|
||||
reporter.reportTransformation(sourceFile, node, `Converted test with \`done\` callback to an \`async\` test.`);
|
||||
const newModifiers = [
|
||||
typescript_1.default.factory.createModifier(typescript_1.default.SyntaxKind.AsyncKeyword),
|
||||
...(typescript_1.default.getModifiers(functionArg) ?? []).filter((mod) => mod.kind !== typescript_1.default.SyntaxKind.AsyncKeyword),
|
||||
];
|
||||
let newFunction;
|
||||
if (typescript_1.default.isArrowFunction(functionArg)) {
|
||||
newFunction = typescript_1.default.factory.updateArrowFunction(functionArg, newModifiers, functionArg.typeParameters, [], // remove parameters
|
||||
functionArg.type, functionArg.equalsGreaterThanToken, newBody ?? typescript_1.default.factory.createBlock([]));
|
||||
}
|
||||
else {
|
||||
// isFunctionExpression
|
||||
newFunction = typescript_1.default.factory.updateFunctionExpression(functionArg, newModifiers, functionArg.asteriskToken, functionArg.name, functionArg.typeParameters, [], // remove parameters
|
||||
functionArg.type, newBody ?? typescript_1.default.factory.createBlock([]));
|
||||
}
|
||||
const newArgs = node.arguments.map((arg) => (arg === functionArg ? newFunction : arg));
|
||||
return typescript_1.default.factory.updateCallExpression(node, node.expression, node.typeArguments, newArgs);
|
||||
}
|
||||
//# sourceMappingURL=jasmine-lifecycle.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+26
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* @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 { RefactorContext } from '../utils/refactor-context';
|
||||
export declare function transformSyntacticSugarMatchers(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
|
||||
export declare function transformAsymmetricMatchers(node: ts.Node, { sourceFile, reporter, pendingVitestValueImports }: RefactorContext): ts.Node;
|
||||
export declare function transformtoHaveBeenCalledBefore(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
|
||||
export declare function transformToHaveClass(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
|
||||
export declare function transformExpectAsync(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
|
||||
export declare function transformComplexMatchers(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
|
||||
export declare function transformArrayWithExactContents(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node | readonly ts.Node[];
|
||||
export declare function transformCalledOnceWith(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node | readonly ts.Node[];
|
||||
export declare function transformWithContext(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
|
||||
export declare function transformExpectNothing(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
|
||||
Generated
Vendored
+401
@@ -0,0 +1,401 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.transformSyntacticSugarMatchers = transformSyntacticSugarMatchers;
|
||||
exports.transformAsymmetricMatchers = transformAsymmetricMatchers;
|
||||
exports.transformtoHaveBeenCalledBefore = transformtoHaveBeenCalledBefore;
|
||||
exports.transformToHaveClass = transformToHaveClass;
|
||||
exports.transformExpectAsync = transformExpectAsync;
|
||||
exports.transformComplexMatchers = transformComplexMatchers;
|
||||
exports.transformArrayWithExactContents = transformArrayWithExactContents;
|
||||
exports.transformCalledOnceWith = transformCalledOnceWith;
|
||||
exports.transformWithContext = transformWithContext;
|
||||
exports.transformExpectNothing = transformExpectNothing;
|
||||
/**
|
||||
* @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`.
|
||||
*/
|
||||
const typescript_1 = __importDefault(require("../../../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
|
||||
const ast_helpers_1 = require("../utils/ast-helpers");
|
||||
const ast_validation_1 = require("../utils/ast-validation");
|
||||
const comment_helpers_1 = require("../utils/comment-helpers");
|
||||
const SUGAR_MATCHER_CHANGES = new Map([
|
||||
['toBeTrue', { newName: 'toBe', newArgs: [typescript_1.default.factory.createTrue()] }],
|
||||
['toBeFalse', { newName: 'toBe', newArgs: [typescript_1.default.factory.createFalse()] }],
|
||||
['toBePositiveInfinity', { newName: 'toBe', newArgs: [typescript_1.default.factory.createIdentifier('Infinity')] }],
|
||||
[
|
||||
'toBeNegativeInfinity',
|
||||
{
|
||||
newName: 'toBe',
|
||||
newArgs: [
|
||||
typescript_1.default.factory.createPrefixUnaryExpression(typescript_1.default.SyntaxKind.MinusToken, typescript_1.default.factory.createIdentifier('Infinity')),
|
||||
],
|
||||
},
|
||||
],
|
||||
['toHaveSize', { newName: 'toHaveLength' }],
|
||||
]);
|
||||
function transformSyntacticSugarMatchers(node, { sourceFile, reporter }) {
|
||||
if (!typescript_1.default.isCallExpression(node) || !typescript_1.default.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);
|
||||
(0, comment_helpers_1.addTodoComment)(node, category);
|
||||
return node;
|
||||
}
|
||||
if (matcherName === 'toThrowMatching') {
|
||||
const category = 'toThrowMatching';
|
||||
reporter.recordTodo(category, sourceFile, node);
|
||||
(0, comment_helpers_1.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 = (0, ast_helpers_1.createPropertyAccess)(pae.expression, mapping.newName);
|
||||
const newArgs = mapping.newArgs ?? [...node.arguments];
|
||||
return typescript_1.default.factory.updateCallExpression(node, newExpression, node.typeArguments, newArgs);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
const ASYMMETRIC_MATCHER_NAMES = [
|
||||
'anything',
|
||||
'any',
|
||||
'stringMatching',
|
||||
'objectContaining',
|
||||
'arrayContaining',
|
||||
'stringContaining',
|
||||
];
|
||||
function transformAsymmetricMatchers(node, { sourceFile, reporter, pendingVitestValueImports }) {
|
||||
if (typescript_1.default.isPropertyAccessExpression(node) &&
|
||||
typescript_1.default.isIdentifier(node.expression) &&
|
||||
node.expression.text === 'jasmine') {
|
||||
const matcherName = node.name.text;
|
||||
if (ASYMMETRIC_MATCHER_NAMES.includes(matcherName)) {
|
||||
(0, ast_helpers_1.addVitestValueImport)(pendingVitestValueImports, 'expect');
|
||||
reporter.reportTransformation(sourceFile, node, `Transformed asymmetric matcher \`jasmine.${matcherName}\` to \`expect.${matcherName}\`.`);
|
||||
return (0, ast_helpers_1.createPropertyAccess)('expect', node.name);
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
function transformtoHaveBeenCalledBefore(node, { sourceFile, reporter }) {
|
||||
if (!typescript_1.default.isCallExpression(node) ||
|
||||
!typescript_1.default.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 (typescript_1.default.isPropertyAccessExpression(expectExpression) && expectExpression.name.text === 'not') {
|
||||
isNegated = true;
|
||||
expectExpression = expectExpression.expression;
|
||||
}
|
||||
if (!typescript_1.default.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) => {
|
||||
const mockedSpy = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)('vi', 'mocked'), undefined, [spyIdentifier]);
|
||||
const mockProperty = (0, ast_helpers_1.createPropertyAccess)(mockedSpy, 'mock');
|
||||
return (0, ast_helpers_1.createPropertyAccess)(mockProperty, 'invocationCallOrder');
|
||||
};
|
||||
const createMinCall = (spyIdentifier) => {
|
||||
return typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)('Math', 'min'), undefined, [
|
||||
typescript_1.default.factory.createSpreadElement(createInvocationOrderAccess(spyIdentifier)),
|
||||
]);
|
||||
};
|
||||
const newExpect = (0, ast_helpers_1.createExpectCallExpression)([createMinCall(spyA)]);
|
||||
const newMatcherName = isNegated ? 'toBeGreaterThanOrEqual' : 'toBeLessThan';
|
||||
return typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(newExpect, newMatcherName), undefined, [createMinCall(spyB)]);
|
||||
}
|
||||
function transformToHaveClass(node, { sourceFile, reporter }) {
|
||||
if (!typescript_1.default.isCallExpression(node) ||
|
||||
!typescript_1.default.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 (typescript_1.default.isPropertyAccessExpression(expectExpression) && expectExpression.name.text === 'not') {
|
||||
isNegated = true;
|
||||
expectExpression = expectExpression.expression;
|
||||
}
|
||||
if (matcherName !== 'toHaveClass') {
|
||||
return node;
|
||||
}
|
||||
reporter.reportTransformation(sourceFile, node, 'Transformed `.toHaveClass()` to a `classList.contains()` check.');
|
||||
const [className] = node.arguments;
|
||||
const newExpectArgs = [];
|
||||
if (typescript_1.default.isCallExpression(expectExpression)) {
|
||||
const [element] = expectExpression.arguments;
|
||||
const classListContains = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)((0, ast_helpers_1.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]);
|
||||
}
|
||||
}
|
||||
else {
|
||||
return node;
|
||||
}
|
||||
const newExpect = (0, ast_helpers_1.createExpectCallExpression)(newExpectArgs);
|
||||
const newMatcher = isNegated ? typescript_1.default.factory.createFalse() : typescript_1.default.factory.createTrue();
|
||||
return typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(newExpect, 'toBe'), undefined, [
|
||||
newMatcher,
|
||||
]);
|
||||
}
|
||||
const ASYNC_MATCHER_CHANGES = new Map([
|
||||
['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 }],
|
||||
]);
|
||||
function transformExpectAsync(node, { sourceFile, reporter }) {
|
||||
if (!typescript_1.default.isCallExpression(node) ||
|
||||
!typescript_1.default.isPropertyAccessExpression(node.expression) ||
|
||||
!typescript_1.default.isCallExpression(node.expression.expression)) {
|
||||
return node;
|
||||
}
|
||||
const matcherCall = node;
|
||||
const matcherPae = node.expression;
|
||||
const expectCall = node.expression.expression;
|
||||
if (!typescript_1.default.isIdentifier(expectCall.expression) || expectCall.expression.text !== 'expectAsync') {
|
||||
return node;
|
||||
}
|
||||
const matcherName = typescript_1.default.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 = (0, ast_helpers_1.createExpectCallExpression)([expectCall.arguments[0]]);
|
||||
let newMatcherChain = (0, ast_helpers_1.createPropertyAccess)(newExpectCall, mapping.base);
|
||||
if (mapping.not) {
|
||||
newMatcherChain = (0, ast_helpers_1.createPropertyAccess)(newMatcherChain, 'not');
|
||||
}
|
||||
newMatcherChain = (0, ast_helpers_1.createPropertyAccess)(newMatcherChain, mapping.matcher);
|
||||
const newMatcherArgs = mapping.keepArgs ? [...matcherCall.arguments] : [];
|
||||
return typescript_1.default.factory.createCallExpression(newMatcherChain, undefined, newMatcherArgs);
|
||||
}
|
||||
if (matcherName) {
|
||||
if (matcherName === 'toBePending') {
|
||||
const category = 'toBePending';
|
||||
reporter.recordTodo(category, sourceFile, node);
|
||||
(0, comment_helpers_1.addTodoComment)(node, category);
|
||||
}
|
||||
else {
|
||||
const category = 'unsupported-expect-async-matcher';
|
||||
reporter.recordTodo(category, sourceFile, node);
|
||||
(0, comment_helpers_1.addTodoComment)(node, category, { name: matcherName });
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
function transformComplexMatchers(node, { sourceFile, reporter }) {
|
||||
if (!typescript_1.default.isCallExpression(node) ||
|
||||
!typescript_1.default.isPropertyAccessExpression(node.expression) ||
|
||||
node.expression.name.text !== 'toEqual' ||
|
||||
node.arguments.length !== 1) {
|
||||
return node;
|
||||
}
|
||||
const argument = node.arguments[0];
|
||||
const jasmineMatcherName = (0, ast_validation_1.getJasmineMethodName)(argument);
|
||||
if (!jasmineMatcherName) {
|
||||
return node;
|
||||
}
|
||||
const expectCall = node.expression.expression;
|
||||
let newMatcherName;
|
||||
let newArgs;
|
||||
let negate = false;
|
||||
switch (jasmineMatcherName) {
|
||||
case 'truthy':
|
||||
newMatcherName = 'toBeTruthy';
|
||||
break;
|
||||
case 'falsy':
|
||||
newMatcherName = 'toBeFalsy';
|
||||
break;
|
||||
case 'empty':
|
||||
newMatcherName = 'toHaveLength';
|
||||
newArgs = [typescript_1.default.factory.createNumericLiteral(0)];
|
||||
break;
|
||||
case 'notEmpty':
|
||||
newMatcherName = 'toHaveLength';
|
||||
newArgs = [typescript_1.default.factory.createNumericLiteral(0)];
|
||||
negate = true;
|
||||
break;
|
||||
case 'is':
|
||||
newMatcherName = 'toBe';
|
||||
if (typescript_1.default.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 (typescript_1.default.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 = (0, ast_helpers_1.createPropertyAccess)(expectExpression, 'not');
|
||||
}
|
||||
const newExpression = (0, ast_helpers_1.createPropertyAccess)(expectExpression, newMatcherName);
|
||||
return typescript_1.default.factory.createCallExpression(newExpression, undefined, newArgs ?? []);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
function transformArrayWithExactContents(node, { sourceFile, reporter }) {
|
||||
if (!typescript_1.default.isExpressionStatement(node) ||
|
||||
!typescript_1.default.isCallExpression(node.expression) ||
|
||||
!typescript_1.default.isPropertyAccessExpression(node.expression.expression) ||
|
||||
node.expression.expression.name.text !== 'toEqual' ||
|
||||
node.expression.arguments.length !== 1) {
|
||||
return node;
|
||||
}
|
||||
const argument = node.expression.arguments[0];
|
||||
if (!(0, ast_validation_1.isJasmineCallExpression)(argument, 'arrayWithExactContents') ||
|
||||
argument.arguments.length !== 1) {
|
||||
return node;
|
||||
}
|
||||
if (!typescript_1.default.isArrayLiteralExpression(argument.arguments[0])) {
|
||||
const category = 'arrayWithExactContents-dynamic-variable';
|
||||
reporter.recordTodo(category, sourceFile, node);
|
||||
(0, comment_helpers_1.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 = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(expectCall, 'toHaveLength'), undefined, [typescript_1.default.factory.createNumericLiteral(arrayLiteral.elements.length)]);
|
||||
const containingCall = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(expectCall, 'toEqual'), undefined, [
|
||||
typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)('expect', 'arrayContaining'), undefined, [arrayLiteral]),
|
||||
]);
|
||||
const lengthStmt = typescript_1.default.factory.createExpressionStatement(lengthCall);
|
||||
const containingStmt = typescript_1.default.factory.createExpressionStatement(containingCall);
|
||||
const category = 'arrayWithExactContents-check';
|
||||
reporter.recordTodo(category, sourceFile, node);
|
||||
(0, comment_helpers_1.addTodoComment)(lengthStmt, category);
|
||||
return [lengthStmt, containingStmt];
|
||||
}
|
||||
function transformCalledOnceWith(node, { sourceFile, reporter }) {
|
||||
if (!typescript_1.default.isExpressionStatement(node)) {
|
||||
return node;
|
||||
}
|
||||
const call = node.expression;
|
||||
if (!typescript_1.default.isCallExpression(call) ||
|
||||
!typescript_1.default.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 = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(expectCall, 'toHaveBeenCalledTimes'), undefined, [typescript_1.default.factory.createNumericLiteral(1)]);
|
||||
const withCall = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(expectCall, 'toHaveBeenCalledWith'), undefined, args);
|
||||
return [
|
||||
typescript_1.default.factory.createExpressionStatement(timesCall),
|
||||
typescript_1.default.factory.createExpressionStatement(withCall),
|
||||
];
|
||||
}
|
||||
function transformWithContext(node, { sourceFile, reporter }) {
|
||||
if (!typescript_1.default.isCallExpression(node) || !typescript_1.default.isPropertyAccessExpression(node.expression)) {
|
||||
return node;
|
||||
}
|
||||
// Traverse the chain of property access expressions to find the .withContext() call
|
||||
let currentExpression = node.expression;
|
||||
const propertyChain = [];
|
||||
while (typescript_1.default.isPropertyAccessExpression(currentExpression)) {
|
||||
if (!typescript_1.default.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 (!typescript_1.default.isCallExpression(withContextCall) ||
|
||||
!typescript_1.default.isPropertyAccessExpression(withContextCall.expression) ||
|
||||
!typescript_1.default.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 (!typescript_1.default.isCallExpression(expectCall) ||
|
||||
!typescript_1.default.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 = expectCall;
|
||||
for (let i = propertyChain.length - 1; i >= 0; i--) {
|
||||
newChain = typescript_1.default.factory.createPropertyAccessExpression(newChain, propertyChain[i]);
|
||||
}
|
||||
return typescript_1.default.factory.updateCallExpression(node, newChain, node.typeArguments, node.arguments);
|
||||
}
|
||||
const newExpectArgs = [...expectCall.arguments, contextMessage];
|
||||
const newExpectCall = typescript_1.default.factory.updateCallExpression(expectCall, expectCall.expression, expectCall.typeArguments, newExpectArgs);
|
||||
// Rebuild the property access chain
|
||||
let newExpression = newExpectCall;
|
||||
for (let i = propertyChain.length - 1; i >= 0; i--) {
|
||||
newExpression = typescript_1.default.factory.createPropertyAccessExpression(newExpression, propertyChain[i]);
|
||||
}
|
||||
return typescript_1.default.factory.updateCallExpression(node, newExpression, node.typeArguments, node.arguments);
|
||||
}
|
||||
function transformExpectNothing(node, { sourceFile, reporter }) {
|
||||
if (!typescript_1.default.isExpressionStatement(node)) {
|
||||
return node;
|
||||
}
|
||||
const call = node.expression;
|
||||
if (!typescript_1.default.isCallExpression(call) ||
|
||||
!typescript_1.default.isPropertyAccessExpression(call.expression) ||
|
||||
!typescript_1.default.isIdentifier(call.expression.name) ||
|
||||
call.expression.name.text !== 'nothing') {
|
||||
return node;
|
||||
}
|
||||
const expectCall = call.expression.expression;
|
||||
if (!typescript_1.default.isCallExpression(expectCall) ||
|
||||
!typescript_1.default.isIdentifier(expectCall.expression) ||
|
||||
expectCall.expression.text !== 'expect' ||
|
||||
expectCall.arguments.length > 0) {
|
||||
return node;
|
||||
}
|
||||
// The statement is `expect().nothing()`, which can be removed.
|
||||
const replacement = typescript_1.default.factory.createEmptyStatement();
|
||||
const originalText = node.getFullText().trim();
|
||||
reporter.reportTransformation(sourceFile, node, 'Removed `expect().nothing()` statement.');
|
||||
const category = 'expect-nothing';
|
||||
reporter.recordTodo(category, sourceFile, node);
|
||||
(0, comment_helpers_1.addTodoComment)(replacement, category);
|
||||
typescript_1.default.addSyntheticLeadingComment(replacement, typescript_1.default.SyntaxKind.SingleLineCommentTrivia, ` ${originalText}`, true);
|
||||
return replacement;
|
||||
}
|
||||
//# sourceMappingURL=jasmine-matcher.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* @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 for miscellaneous Jasmine APIs that don't
|
||||
* fit into other categories. This includes timer mocks (`jasmine.clock`), the `fail()`
|
||||
* function, and configuration settings like `jasmine.DEFAULT_TIMEOUT_INTERVAL`. It also
|
||||
* includes logic to identify and add TODO comments for unsupported Jasmine features.
|
||||
*/
|
||||
import ts from '../../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
|
||||
import { RefactorContext } from '../utils/refactor-context';
|
||||
export declare function transformTimerMocks(node: ts.Node, { sourceFile, reporter, pendingVitestValueImports }: RefactorContext): ts.Node;
|
||||
export declare function transformFail(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
|
||||
export declare function transformDefaultTimeoutInterval(node: ts.Node, { sourceFile, reporter, pendingVitestValueImports }: RefactorContext): ts.Node;
|
||||
export declare function transformGlobalFunctions(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
|
||||
export declare function transformUnsupportedJasmineCalls(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
|
||||
export declare function transformUnknownJasmineProperties(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
|
||||
Generated
Vendored
+174
@@ -0,0 +1,174 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.transformTimerMocks = transformTimerMocks;
|
||||
exports.transformFail = transformFail;
|
||||
exports.transformDefaultTimeoutInterval = transformDefaultTimeoutInterval;
|
||||
exports.transformGlobalFunctions = transformGlobalFunctions;
|
||||
exports.transformUnsupportedJasmineCalls = transformUnsupportedJasmineCalls;
|
||||
exports.transformUnknownJasmineProperties = transformUnknownJasmineProperties;
|
||||
/**
|
||||
* @fileoverview This file contains transformers for miscellaneous Jasmine APIs that don't
|
||||
* fit into other categories. This includes timer mocks (`jasmine.clock`), the `fail()`
|
||||
* function, and configuration settings like `jasmine.DEFAULT_TIMEOUT_INTERVAL`. It also
|
||||
* includes logic to identify and add TODO comments for unsupported Jasmine features.
|
||||
*/
|
||||
const typescript_1 = __importDefault(require("../../../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
|
||||
const ast_helpers_1 = require("../utils/ast-helpers");
|
||||
const ast_validation_1 = require("../utils/ast-validation");
|
||||
const comment_helpers_1 = require("../utils/comment-helpers");
|
||||
function transformTimerMocks(node, { sourceFile, reporter, pendingVitestValueImports }) {
|
||||
if (!typescript_1.default.isCallExpression(node) ||
|
||||
!typescript_1.default.isPropertyAccessExpression(node.expression) ||
|
||||
!typescript_1.default.isIdentifier(node.expression.name)) {
|
||||
return node;
|
||||
}
|
||||
const pae = node.expression;
|
||||
const clockCall = pae.expression;
|
||||
if (!(0, ast_validation_1.isJasmineCallExpression)(clockCall, 'clock')) {
|
||||
return node;
|
||||
}
|
||||
let newMethodName;
|
||||
switch (pae.name.text) {
|
||||
case 'install':
|
||||
newMethodName = 'useFakeTimers';
|
||||
break;
|
||||
case 'tick':
|
||||
newMethodName = 'advanceTimersByTime';
|
||||
break;
|
||||
case 'uninstall':
|
||||
newMethodName = 'useRealTimers';
|
||||
break;
|
||||
case 'mockDate':
|
||||
newMethodName = 'setSystemTime';
|
||||
break;
|
||||
}
|
||||
if (newMethodName) {
|
||||
(0, ast_helpers_1.addVitestValueImport)(pendingVitestValueImports, 'vi');
|
||||
reporter.reportTransformation(sourceFile, node, `Transformed \`jasmine.clock().${pae.name.text}\` to \`vi.${newMethodName}\`.`);
|
||||
let newArgs = node.arguments;
|
||||
if (newMethodName === 'useFakeTimers') {
|
||||
newArgs = [];
|
||||
}
|
||||
if (newMethodName === 'setSystemTime' && node.arguments.length === 0) {
|
||||
newArgs = [
|
||||
typescript_1.default.factory.createNewExpression(typescript_1.default.factory.createIdentifier('Date'), undefined, []),
|
||||
];
|
||||
}
|
||||
return (0, ast_helpers_1.createViCallExpression)(newMethodName, newArgs);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
function transformFail(node, { sourceFile, reporter }) {
|
||||
if (typescript_1.default.isExpressionStatement(node) &&
|
||||
typescript_1.default.isCallExpression(node.expression) &&
|
||||
typescript_1.default.isIdentifier(node.expression.expression) &&
|
||||
node.expression.expression.text === 'fail') {
|
||||
reporter.reportTransformation(sourceFile, node, 'Transformed `fail()` to `throw new Error()`.');
|
||||
const reason = node.expression.arguments[0];
|
||||
const replacement = typescript_1.default.factory.createThrowStatement(typescript_1.default.factory.createNewExpression(typescript_1.default.factory.createIdentifier('Error'), undefined, reason ? [reason] : []));
|
||||
return typescript_1.default.setOriginalNode(typescript_1.default.setTextRange(replacement, node), node);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
function transformDefaultTimeoutInterval(node, { sourceFile, reporter, pendingVitestValueImports }) {
|
||||
if (typescript_1.default.isExpressionStatement(node) &&
|
||||
typescript_1.default.isBinaryExpression(node.expression) &&
|
||||
node.expression.operatorToken.kind === typescript_1.default.SyntaxKind.EqualsToken) {
|
||||
const assignment = node.expression;
|
||||
if (typescript_1.default.isPropertyAccessExpression(assignment.left) &&
|
||||
typescript_1.default.isIdentifier(assignment.left.expression) &&
|
||||
assignment.left.expression.text === 'jasmine' &&
|
||||
assignment.left.name.text === 'DEFAULT_TIMEOUT_INTERVAL') {
|
||||
(0, ast_helpers_1.addVitestValueImport)(pendingVitestValueImports, 'vi');
|
||||
reporter.reportTransformation(sourceFile, node, 'Transformed `jasmine.DEFAULT_TIMEOUT_INTERVAL` to `vi.setConfig()`.');
|
||||
const timeoutValue = assignment.right;
|
||||
const setConfigCall = (0, ast_helpers_1.createViCallExpression)('setConfig', [
|
||||
typescript_1.default.factory.createObjectLiteralExpression([typescript_1.default.factory.createPropertyAssignment('testTimeout', timeoutValue)], false),
|
||||
]);
|
||||
return typescript_1.default.factory.updateExpressionStatement(node, setConfigCall);
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
function transformGlobalFunctions(node, { sourceFile, reporter }) {
|
||||
if (typescript_1.default.isCallExpression(node) &&
|
||||
typescript_1.default.isIdentifier(node.expression) &&
|
||||
(node.expression.text === 'setSpecProperty' || node.expression.text === 'setSuiteProperty')) {
|
||||
const functionName = node.expression.text;
|
||||
reporter.reportTransformation(sourceFile, node, `Found unsupported global function \`${functionName}\`.`);
|
||||
const category = 'unsupported-global-function';
|
||||
reporter.recordTodo(category, sourceFile, node);
|
||||
(0, comment_helpers_1.addTodoComment)(node, category, { name: functionName });
|
||||
}
|
||||
return node;
|
||||
}
|
||||
const UNSUPPORTED_JASMINE_CALLS_CATEGORIES = new Set([
|
||||
'addMatchers',
|
||||
'addCustomEqualityTester',
|
||||
'mapContaining',
|
||||
'setContaining',
|
||||
]);
|
||||
// A type guard to ensure that the methodName is one of the categories handled by this transformer.
|
||||
function isUnsupportedJasmineCall(methodName) {
|
||||
return UNSUPPORTED_JASMINE_CALLS_CATEGORIES.has(methodName);
|
||||
}
|
||||
function transformUnsupportedJasmineCalls(node, { sourceFile, reporter }) {
|
||||
const methodName = (0, ast_validation_1.getJasmineMethodName)(node);
|
||||
if (methodName && isUnsupportedJasmineCall(methodName)) {
|
||||
reporter.reportTransformation(sourceFile, node, `Found unsupported call \`jasmine.${methodName}\`.`);
|
||||
reporter.recordTodo(methodName, sourceFile, node);
|
||||
(0, comment_helpers_1.addTodoComment)(node, methodName);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
// If any additional properties are added to transforms, they should also be added to this list.
|
||||
const HANDLED_JASMINE_PROPERTIES = new Set([
|
||||
// Spies
|
||||
'createSpy',
|
||||
'createSpyObj',
|
||||
'spyOnAllFunctions',
|
||||
// Clock
|
||||
'clock',
|
||||
// Matchers
|
||||
'any',
|
||||
'anything',
|
||||
'stringMatching',
|
||||
'objectContaining',
|
||||
'arrayContaining',
|
||||
'arrayWithExactContents',
|
||||
'truthy',
|
||||
'falsy',
|
||||
'empty',
|
||||
'notEmpty',
|
||||
'mapContaining',
|
||||
'setContaining',
|
||||
// Other
|
||||
'DEFAULT_TIMEOUT_INTERVAL',
|
||||
'addMatchers',
|
||||
'addCustomEqualityTester',
|
||||
]);
|
||||
function transformUnknownJasmineProperties(node, { sourceFile, reporter }) {
|
||||
if (typescript_1.default.isPropertyAccessExpression(node) &&
|
||||
typescript_1.default.isIdentifier(node.expression) &&
|
||||
node.expression.text === 'jasmine') {
|
||||
const propName = node.name.text;
|
||||
if (!HANDLED_JASMINE_PROPERTIES.has(propName)) {
|
||||
reporter.reportTransformation(sourceFile, node, `Found unknown jasmine property \`jasmine.${propName}\`.`);
|
||||
const category = 'unknown-jasmine-property';
|
||||
reporter.recordTodo(category, sourceFile, node);
|
||||
(0, comment_helpers_1.addTodoComment)(node, category, { name: propName });
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
//# sourceMappingURL=jasmine-misc.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+19
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* @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 dedicated to converting Jasmine's spying
|
||||
* functionality to Vitest's mocking APIs. It handles the creation of spies (`spyOn`,
|
||||
* `createSpy`, `createSpyObj`), spy strategies (`and.returnValue`, `and.callFake`),
|
||||
* and the inspection of spy calls (`spy.calls.reset`, `spy.calls.mostRecent`).
|
||||
*/
|
||||
import ts from '../../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
|
||||
import { RefactorContext } from '../utils/refactor-context';
|
||||
export declare function transformSpies(node: ts.Node, refactorCtx: RefactorContext): ts.Node;
|
||||
export declare function transformCreateSpyObj(node: ts.Node, { sourceFile, reporter, pendingVitestValueImports }: RefactorContext): ts.Node;
|
||||
export declare function transformSpyReset(node: ts.Node, { sourceFile, reporter }: RefactorContext): ts.Node;
|
||||
export declare function transformSpyCallInspection(node: ts.Node, refactorCtx: RefactorContext): ts.Node;
|
||||
Generated
Vendored
+316
@@ -0,0 +1,316 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.transformSpies = transformSpies;
|
||||
exports.transformCreateSpyObj = transformCreateSpyObj;
|
||||
exports.transformSpyReset = transformSpyReset;
|
||||
exports.transformSpyCallInspection = transformSpyCallInspection;
|
||||
/**
|
||||
* @fileoverview This file contains transformers dedicated to converting Jasmine's spying
|
||||
* functionality to Vitest's mocking APIs. It handles the creation of spies (`spyOn`,
|
||||
* `createSpy`, `createSpyObj`), spy strategies (`and.returnValue`, `and.callFake`),
|
||||
* and the inspection of spy calls (`spy.calls.reset`, `spy.calls.mostRecent`).
|
||||
*/
|
||||
const typescript_1 = __importDefault(require("../../../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
|
||||
const ast_helpers_1 = require("../utils/ast-helpers");
|
||||
const ast_validation_1 = require("../utils/ast-validation");
|
||||
const comment_helpers_1 = require("../utils/comment-helpers");
|
||||
function transformSpies(node, refactorCtx) {
|
||||
const { sourceFile, reporter, pendingVitestValueImports } = refactorCtx;
|
||||
if (!typescript_1.default.isCallExpression(node)) {
|
||||
return node;
|
||||
}
|
||||
if (typescript_1.default.isIdentifier(node.expression) &&
|
||||
(node.expression.text === 'spyOn' || node.expression.text === 'spyOnProperty')) {
|
||||
(0, ast_helpers_1.addVitestValueImport)(pendingVitestValueImports, 'vi');
|
||||
reporter.reportTransformation(sourceFile, node, `Transformed \`${node.expression.text}\` to \`vi.spyOn\`.`);
|
||||
return typescript_1.default.factory.updateCallExpression(node, (0, ast_helpers_1.createPropertyAccess)('vi', 'spyOn'), node.typeArguments, node.arguments);
|
||||
}
|
||||
if (typescript_1.default.isPropertyAccessExpression(node.expression)) {
|
||||
const pae = node.expression;
|
||||
if (typescript_1.default.isPropertyAccessExpression(pae.expression) &&
|
||||
typescript_1.default.isIdentifier(pae.expression.name) &&
|
||||
pae.expression.name.text === 'and') {
|
||||
const spyCall = pae.expression.expression;
|
||||
let newMethodName;
|
||||
if (typescript_1.default.isIdentifier(pae.name)) {
|
||||
const strategyName = pae.name.text;
|
||||
switch (strategyName) {
|
||||
case 'returnValue':
|
||||
newMethodName = 'mockReturnValue';
|
||||
break;
|
||||
case 'resolveTo':
|
||||
newMethodName = 'mockResolvedValue';
|
||||
break;
|
||||
case 'rejectWith':
|
||||
newMethodName = 'mockRejectedValue';
|
||||
break;
|
||||
case 'returnValues': {
|
||||
reporter.reportTransformation(sourceFile, node, 'Transformed `.and.returnValues()` to chained `.mockReturnValueOnce()` calls.');
|
||||
const returnValues = node.arguments;
|
||||
if (returnValues.length === 0) {
|
||||
// No values, so it's a no-op. Just transform the spyOn call.
|
||||
return transformSpies(spyCall, refactorCtx);
|
||||
}
|
||||
// spy.and.returnValues(a, b) -> spy.mockReturnValueOnce(a).mockReturnValueOnce(b)
|
||||
let chainedCall = spyCall;
|
||||
for (const value of returnValues) {
|
||||
const mockCall = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(chainedCall, 'mockReturnValueOnce'), undefined, [value]);
|
||||
chainedCall = mockCall;
|
||||
}
|
||||
return chainedCall;
|
||||
}
|
||||
case 'callFake':
|
||||
newMethodName = 'mockImplementation';
|
||||
break;
|
||||
case 'callThrough':
|
||||
reporter.reportTransformation(sourceFile, node, 'Removed redundant `.and.callThrough()` call.');
|
||||
return transformSpies(spyCall, refactorCtx); // .and.callThrough() is redundant, just transform spyOn.
|
||||
case 'stub': {
|
||||
reporter.reportTransformation(sourceFile, node, 'Transformed `.and.stub()` to `.mockImplementation()`.');
|
||||
const newExpression = (0, ast_helpers_1.createPropertyAccess)(spyCall, 'mockImplementation');
|
||||
const arrowFn = typescript_1.default.factory.createArrowFunction(undefined, undefined, [], undefined, typescript_1.default.factory.createToken(typescript_1.default.SyntaxKind.EqualsGreaterThanToken), typescript_1.default.factory.createBlock([], /* multiline */ true));
|
||||
return typescript_1.default.factory.createCallExpression(newExpression, undefined, [arrowFn]);
|
||||
}
|
||||
case 'throwError': {
|
||||
reporter.reportTransformation(sourceFile, node, 'Transformed `.and.throwError()` to `.mockImplementation()`.');
|
||||
const errorArg = node.arguments[0];
|
||||
const throwStatement = typescript_1.default.factory.createThrowStatement(typescript_1.default.isNewExpression(errorArg)
|
||||
? errorArg
|
||||
: typescript_1.default.factory.createNewExpression(typescript_1.default.factory.createIdentifier('Error'), undefined, node.arguments));
|
||||
const arrowFunction = typescript_1.default.factory.createArrowFunction(undefined, undefined, [], undefined, typescript_1.default.factory.createToken(typescript_1.default.SyntaxKind.EqualsGreaterThanToken), typescript_1.default.factory.createBlock([throwStatement], true));
|
||||
const newExpression = (0, ast_helpers_1.createPropertyAccess)(spyCall, 'mockImplementation');
|
||||
return typescript_1.default.factory.createCallExpression(newExpression, undefined, [arrowFunction]);
|
||||
}
|
||||
default: {
|
||||
const category = 'unsupported-spy-strategy';
|
||||
reporter.recordTodo(category, sourceFile, node);
|
||||
(0, comment_helpers_1.addTodoComment)(node, category, { name: strategyName });
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (newMethodName) {
|
||||
reporter.reportTransformation(sourceFile, node, `Transformed spy strategy \`.and.${strategyName}()\` to \`.${newMethodName}()\`.`);
|
||||
const newExpression = typescript_1.default.factory.updatePropertyAccessExpression(pae, spyCall, typescript_1.default.factory.createIdentifier(newMethodName));
|
||||
return typescript_1.default.factory.updateCallExpression(node, newExpression, node.typeArguments, node.arguments);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const jasmineMethodName = (0, ast_validation_1.getJasmineMethodName)(node);
|
||||
switch (jasmineMethodName) {
|
||||
case 'createSpy':
|
||||
(0, ast_helpers_1.addVitestValueImport)(pendingVitestValueImports, 'vi');
|
||||
reporter.reportTransformation(sourceFile, node, 'Transformed `jasmine.createSpy()` to `vi.fn()`.');
|
||||
// jasmine.createSpy(name, originalFn) -> vi.fn(originalFn)
|
||||
return (0, ast_helpers_1.createViCallExpression)('fn', node.arguments.length > 1 ? [node.arguments[1]] : []);
|
||||
case 'spyOnAllFunctions': {
|
||||
reporter.reportTransformation(sourceFile, node, 'Found unsupported `jasmine.spyOnAllFunctions()`.');
|
||||
const category = 'spyOnAllFunctions';
|
||||
reporter.recordTodo(category, sourceFile, node);
|
||||
(0, comment_helpers_1.addTodoComment)(node, category);
|
||||
return node;
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
function transformCreateSpyObj(node, { sourceFile, reporter, pendingVitestValueImports }) {
|
||||
if (!(0, ast_validation_1.isJasmineCallExpression)(node, 'createSpyObj')) {
|
||||
return node;
|
||||
}
|
||||
(0, ast_helpers_1.addVitestValueImport)(pendingVitestValueImports, 'vi');
|
||||
reporter.reportTransformation(sourceFile, node, 'Transformed `jasmine.createSpyObj()` to an object literal with `vi.fn()`.');
|
||||
const firstArg = node.arguments[0];
|
||||
const hasBaseName = typescript_1.default.isStringLiteral(firstArg);
|
||||
const baseName = hasBaseName ? firstArg.text : undefined;
|
||||
const methods = hasBaseName ? node.arguments[1] : firstArg;
|
||||
const propertiesArg = hasBaseName ? node.arguments[2] : node.arguments[1];
|
||||
let properties = [];
|
||||
if (node.arguments.length < 2 && hasBaseName) {
|
||||
const category = 'createSpyObj-single-argument';
|
||||
reporter.recordTodo(category, sourceFile, node);
|
||||
(0, comment_helpers_1.addTodoComment)(node, category);
|
||||
return node;
|
||||
}
|
||||
if (typescript_1.default.isArrayLiteralExpression(methods)) {
|
||||
properties = createSpyObjWithArray(methods, baseName);
|
||||
}
|
||||
else if (typescript_1.default.isObjectLiteralExpression(methods)) {
|
||||
properties = createSpyObjWithObject(methods, baseName);
|
||||
}
|
||||
else {
|
||||
const category = 'createSpyObj-dynamic-variable';
|
||||
reporter.recordTodo(category, sourceFile, node);
|
||||
(0, comment_helpers_1.addTodoComment)(node, category);
|
||||
return node;
|
||||
}
|
||||
if (propertiesArg) {
|
||||
if (typescript_1.default.isObjectLiteralExpression(propertiesArg)) {
|
||||
properties.push(...propertiesArg.properties);
|
||||
}
|
||||
else {
|
||||
const category = 'createSpyObj-dynamic-property-map';
|
||||
reporter.recordTodo(category, sourceFile, node);
|
||||
(0, comment_helpers_1.addTodoComment)(node, category);
|
||||
}
|
||||
}
|
||||
return typescript_1.default.factory.createObjectLiteralExpression(properties, true);
|
||||
}
|
||||
function createSpyObjWithArray(methods, baseName) {
|
||||
return methods.elements
|
||||
.map((element) => {
|
||||
if (typescript_1.default.isStringLiteral(element)) {
|
||||
const mockFn = (0, ast_helpers_1.createViCallExpression)('fn');
|
||||
const methodName = element.text;
|
||||
let finalExpression = mockFn;
|
||||
if (baseName) {
|
||||
finalExpression = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(finalExpression, 'mockName'), undefined, [typescript_1.default.factory.createStringLiteral(`${baseName}.${methodName}`)]);
|
||||
}
|
||||
return typescript_1.default.factory.createPropertyAssignment(typescript_1.default.factory.createIdentifier(methodName), finalExpression);
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.filter((p) => !!p);
|
||||
}
|
||||
function createSpyObjWithObject(methods, baseName) {
|
||||
return methods.properties
|
||||
.map((prop) => {
|
||||
if (typescript_1.default.isPropertyAssignment(prop) && typescript_1.default.isIdentifier(prop.name)) {
|
||||
const methodName = prop.name.text;
|
||||
const returnValue = prop.initializer;
|
||||
let mockFn = (0, ast_helpers_1.createViCallExpression)('fn');
|
||||
if (baseName) {
|
||||
mockFn = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)(mockFn, 'mockName'), undefined, [typescript_1.default.factory.createStringLiteral(`${baseName}.${methodName}`)]);
|
||||
}
|
||||
const mockReturnValue = (0, ast_helpers_1.createPropertyAccess)(mockFn, 'mockReturnValue');
|
||||
return typescript_1.default.factory.createPropertyAssignment(typescript_1.default.factory.createIdentifier(methodName), typescript_1.default.factory.createCallExpression(mockReturnValue, undefined, [returnValue]));
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.filter((p) => !!p);
|
||||
}
|
||||
function transformSpyReset(node, { sourceFile, reporter }) {
|
||||
if (typescript_1.default.isCallExpression(node) &&
|
||||
typescript_1.default.isPropertyAccessExpression(node.expression) &&
|
||||
typescript_1.default.isIdentifier(node.expression.name) &&
|
||||
node.expression.name.text === 'reset' &&
|
||||
typescript_1.default.isPropertyAccessExpression(node.expression.expression)) {
|
||||
const callsPae = node.expression.expression;
|
||||
if (typescript_1.default.isIdentifier(callsPae.name) && callsPae.name.text === 'calls') {
|
||||
reporter.reportTransformation(sourceFile, node, 'Transformed `spy.calls.reset()` to `.mockClear()`.');
|
||||
const spyIdentifier = callsPae.expression;
|
||||
const newExpression = (0, ast_helpers_1.createPropertyAccess)(spyIdentifier, 'mockClear');
|
||||
return typescript_1.default.factory.updateCallExpression(node, newExpression, node.typeArguments, []);
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
function getSpyIdentifierFromCalls(node) {
|
||||
if (typescript_1.default.isIdentifier(node.name) && node.name.text === 'calls') {
|
||||
return node.expression;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
function createMockedSpyMockProperty(spyIdentifier, pendingVitestValueImports) {
|
||||
(0, ast_helpers_1.addVitestValueImport)(pendingVitestValueImports, 'vi');
|
||||
const mockedSpy = typescript_1.default.factory.createCallExpression((0, ast_helpers_1.createPropertyAccess)('vi', 'mocked'), undefined, [spyIdentifier]);
|
||||
return (0, ast_helpers_1.createPropertyAccess)(mockedSpy, 'mock');
|
||||
}
|
||||
function transformMostRecentArgs(node, { sourceFile, reporter, pendingVitestValueImports }) {
|
||||
// Check 1: Is it a property access for `.args`?
|
||||
if (!typescript_1.default.isPropertyAccessExpression(node) ||
|
||||
!typescript_1.default.isIdentifier(node.name) ||
|
||||
node.name.text !== 'args') {
|
||||
return node;
|
||||
}
|
||||
// Check 2: Is the preceding expression a call expression?
|
||||
const mostRecentCall = node.expression;
|
||||
if (!typescript_1.default.isCallExpression(mostRecentCall) ||
|
||||
!typescript_1.default.isPropertyAccessExpression(mostRecentCall.expression)) {
|
||||
return node;
|
||||
}
|
||||
// Check 3: Is it a call to `.mostRecent`?
|
||||
const mostRecentPae = mostRecentCall.expression;
|
||||
if (!typescript_1.default.isIdentifier(mostRecentPae.name) ||
|
||||
mostRecentPae.name.text !== 'mostRecent' ||
|
||||
!typescript_1.default.isPropertyAccessExpression(mostRecentPae.expression)) {
|
||||
return node;
|
||||
}
|
||||
// Check 4: Can we get the spy identifier from `spy.calls`?
|
||||
const spyIdentifier = getSpyIdentifierFromCalls(mostRecentPae.expression);
|
||||
if (!spyIdentifier) {
|
||||
return node;
|
||||
}
|
||||
// If all checks pass, perform the transformation.
|
||||
reporter.reportTransformation(sourceFile, node, 'Transformed `spy.calls.mostRecent().args` to `vi.mocked(spy).mock.lastCall`.');
|
||||
const mockProperty = createMockedSpyMockProperty(spyIdentifier, pendingVitestValueImports);
|
||||
return (0, ast_helpers_1.createPropertyAccess)(mockProperty, 'lastCall');
|
||||
}
|
||||
function transformSpyCallInspection(node, refactorCtx) {
|
||||
const mostRecentArgsTransformed = transformMostRecentArgs(node, refactorCtx);
|
||||
if (mostRecentArgsTransformed !== node) {
|
||||
return mostRecentArgsTransformed;
|
||||
}
|
||||
if (!typescript_1.default.isCallExpression(node) || !typescript_1.default.isPropertyAccessExpression(node.expression)) {
|
||||
return node;
|
||||
}
|
||||
const { sourceFile, reporter, pendingVitestValueImports } = refactorCtx;
|
||||
const pae = node.expression; // e.g., mySpy.calls.count
|
||||
const spyIdentifier = typescript_1.default.isPropertyAccessExpression(pae.expression)
|
||||
? getSpyIdentifierFromCalls(pae.expression)
|
||||
: undefined;
|
||||
if (spyIdentifier) {
|
||||
const mockProperty = createMockedSpyMockProperty(spyIdentifier, pendingVitestValueImports);
|
||||
const callsProperty = (0, ast_helpers_1.createPropertyAccess)(mockProperty, 'calls');
|
||||
const callName = pae.name.text;
|
||||
let newExpression;
|
||||
let message;
|
||||
switch (callName) {
|
||||
case 'any':
|
||||
message = 'Transformed `spy.calls.any()` to a check on `mock.calls.length`.';
|
||||
newExpression = typescript_1.default.factory.createBinaryExpression((0, ast_helpers_1.createPropertyAccess)(callsProperty, 'length'), typescript_1.default.SyntaxKind.GreaterThanToken, typescript_1.default.factory.createNumericLiteral(0));
|
||||
break;
|
||||
case 'count':
|
||||
message = 'Transformed `spy.calls.count()` to `mock.calls.length`.';
|
||||
newExpression = (0, ast_helpers_1.createPropertyAccess)(callsProperty, 'length');
|
||||
break;
|
||||
case 'first':
|
||||
message = 'Transformed `spy.calls.first()` to `mock.calls[0]`.';
|
||||
newExpression = typescript_1.default.factory.createElementAccessExpression(callsProperty, 0);
|
||||
break;
|
||||
case 'all':
|
||||
case 'allArgs':
|
||||
message = `Transformed \`spy.calls.${callName}()\` to \`mock.calls\`.`;
|
||||
newExpression = callsProperty;
|
||||
break;
|
||||
case 'argsFor':
|
||||
message = 'Transformed `spy.calls.argsFor()` to `mock.calls[i]`.';
|
||||
newExpression = typescript_1.default.factory.createElementAccessExpression(callsProperty, node.arguments[0]);
|
||||
break;
|
||||
case 'mostRecent':
|
||||
if (!typescript_1.default.isPropertyAccessExpression(node.parent) ||
|
||||
!typescript_1.default.isIdentifier(node.parent.name) ||
|
||||
node.parent.name.text !== 'args') {
|
||||
const category = 'mostRecent-without-args';
|
||||
reporter.recordTodo(category, sourceFile, node);
|
||||
(0, comment_helpers_1.addTodoComment)(node, category);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
if (newExpression && message) {
|
||||
reporter.reportTransformation(sourceFile, node, message);
|
||||
return newExpression;
|
||||
}
|
||||
}
|
||||
return node;
|
||||
}
|
||||
//# sourceMappingURL=jasmine-spy.js.map
|
||||
Generated
Vendored
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+16
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* @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 a transformer that migrates Jasmine type definitions to
|
||||
* their Vitest equivalents. It handles the conversion of types like `jasmine.Spy` and
|
||||
* `jasmine.SpyObj` to Vitest's `Mock` and `MockedObject` types, and ensures that the
|
||||
* necessary `vitest` imports are added to the file.
|
||||
*/
|
||||
import ts from '../../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
|
||||
import { RefactorContext } from '../utils/refactor-context';
|
||||
export declare function transformJasmineTypes(node: ts.Node, { sourceFile, reporter, pendingVitestTypeImports }: RefactorContext): ts.Node;
|
||||
Generated
Vendored
+64
@@ -0,0 +1,64 @@
|
||||
"use strict";
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.transformJasmineTypes = transformJasmineTypes;
|
||||
/**
|
||||
* @fileoverview This file contains a transformer that migrates Jasmine type definitions to
|
||||
* their Vitest equivalents. It handles the conversion of types like `jasmine.Spy` and
|
||||
* `jasmine.SpyObj` to Vitest's `Mock` and `MockedObject` types, and ensures that the
|
||||
* necessary `vitest` imports are added to the file.
|
||||
*/
|
||||
const typescript_1 = __importDefault(require("../../../third_party/github.com/Microsoft/TypeScript/lib/typescript"));
|
||||
const ast_helpers_1 = require("../utils/ast-helpers");
|
||||
function transformJasmineTypes(node, { sourceFile, reporter, pendingVitestTypeImports }) {
|
||||
const typeNameNode = typescript_1.default.isTypeReferenceNode(node) ? node.typeName : node;
|
||||
if (!typescript_1.default.isQualifiedName(typeNameNode) ||
|
||||
!typescript_1.default.isIdentifier(typeNameNode.left) ||
|
||||
typeNameNode.left.text !== 'jasmine') {
|
||||
return node;
|
||||
}
|
||||
const jasmineTypeName = typeNameNode.right.text;
|
||||
switch (jasmineTypeName) {
|
||||
case 'Spy': {
|
||||
const vitestTypeName = 'Mock';
|
||||
reporter.reportTransformation(sourceFile, node, `Transformed type \`jasmine.Spy\` to \`${vitestTypeName}\`.`);
|
||||
(0, ast_helpers_1.addVitestTypeImport)(pendingVitestTypeImports, vitestTypeName);
|
||||
return typescript_1.default.factory.createIdentifier(vitestTypeName);
|
||||
}
|
||||
case 'SpyObj': {
|
||||
const vitestTypeName = 'MockedObject';
|
||||
reporter.reportTransformation(sourceFile, node, `Transformed type \`jasmine.SpyObj\` to \`${vitestTypeName}\`.`);
|
||||
(0, ast_helpers_1.addVitestTypeImport)(pendingVitestTypeImports, vitestTypeName);
|
||||
if (typescript_1.default.isTypeReferenceNode(node)) {
|
||||
return typescript_1.default.factory.updateTypeReferenceNode(node, typescript_1.default.factory.createIdentifier(vitestTypeName), node.typeArguments);
|
||||
}
|
||||
return typescript_1.default.factory.createIdentifier(vitestTypeName);
|
||||
}
|
||||
case 'Any':
|
||||
reporter.reportTransformation(sourceFile, node, `Transformed type \`jasmine.Any\` to \`any\`.`);
|
||||
return typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.AnyKeyword);
|
||||
case 'ObjectContaining': {
|
||||
const typeArguments = typescript_1.default.isTypeReferenceNode(node) ? node.typeArguments : undefined;
|
||||
if (typeArguments && typeArguments.length > 0) {
|
||||
reporter.reportTransformation(sourceFile, node, `Transformed type \`jasmine.ObjectContaining\` to \`Partial\`.`);
|
||||
return typescript_1.default.factory.createTypeReferenceNode('Partial', typeArguments);
|
||||
}
|
||||
reporter.reportTransformation(sourceFile, node, `Transformed type \`jasmine.ObjectContaining\` to \`object\`.`);
|
||||
return typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.ObjectKeyword);
|
||||
}
|
||||
case 'DoneFn':
|
||||
reporter.reportTransformation(sourceFile, node, 'Transformed type `jasmine.DoneFn` to `() => void`.');
|
||||
return typescript_1.default.factory.createFunctionTypeNode(undefined, [], typescript_1.default.factory.createKeywordTypeNode(typescript_1.default.SyntaxKind.VoidKeyword));
|
||||
}
|
||||
return node;
|
||||
}
|
||||
//# sourceMappingURL=jasmine-type.js.map
|
||||
Generated
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"file":"jasmine-type.js","sourceRoot":"","sources":["jasmine-type.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;;;AAaH,sDAyFC;AApGD;;;;;GAKG;AAEH,qHAAqF;AACrF,sDAA2D;AAG3D,SAAgB,qBAAqB,CACnC,IAAa,EACb,EAAE,UAAU,EAAE,QAAQ,EAAE,wBAAwB,EAAmB;IAEnE,MAAM,YAAY,GAAG,oBAAE,CAAC,mBAAmB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC;IACzE,IACE,CAAC,oBAAE,CAAC,eAAe,CAAC,YAAY,CAAC;QACjC,CAAC,oBAAE,CAAC,YAAY,CAAC,YAAY,CAAC,IAAI,CAAC;QACnC,YAAY,CAAC,IAAI,CAAC,IAAI,KAAK,SAAS,EACpC,CAAC;QACD,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,eAAe,GAAG,YAAY,CAAC,KAAK,CAAC,IAAI,CAAC;IAEhD,QAAQ,eAAe,EAAE,CAAC;QACxB,KAAK,KAAK,CAAC,CAAC,CAAC;YACX,MAAM,cAAc,GAAG,MAAM,CAAC;YAC9B,QAAQ,CAAC,oBAAoB,CAC3B,UAAU,EACV,IAAI,EACJ,yCAAyC,cAAc,KAAK,CAC7D,CAAC;YACF,IAAA,iCAAmB,EAAC,wBAAwB,EAAE,cAAc,CAAC,CAAC;YAE9D,OAAO,oBAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,cAAc,CAAC,CAAC;QACrD,CAAC;QACD,KAAK,QAAQ,CAAC,CAAC,CAAC;YACd,MAAM,cAAc,GAAG,cAAc,CAAC;YACtC,QAAQ,CAAC,oBAAoB,CAC3B,UAAU,EACV,IAAI,EACJ,4CAA4C,cAAc,KAAK,CAChE,CAAC;YACF,IAAA,iCAAmB,EAAC,wBAAwB,EAAE,cAAc,CAAC,CAAC;YAE9D,IAAI,oBAAE,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE,CAAC;gBACjC,OAAO,oBAAE,CAAC,OAAO,CAAC,uBAAuB,CACvC,IAAI,EACJ,oBAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,cAAc,CAAC,EAC3C,IAAI,CAAC,aAAa,CACnB,CAAC;YACJ,CAAC;YAED,OAAO,oBAAE,CAAC,OAAO,CAAC,gBAAgB,CAAC,cAAc,CAAC,CAAC;QACrD,CAAC;QACD,KAAK,KAAK;YACR,QAAQ,CAAC,oBAAoB,CAC3B,UAAU,EACV,IAAI,EACJ,8CAA8C,CAC/C,CAAC;YAEF,OAAO,oBAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,oBAAE,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;QACpE,KAAK,kBAAkB,CAAC,CAAC,CAAC;YACxB,MAAM,aAAa,GAAG,oBAAE,CAAC,mBAAmB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,SAAS,CAAC;YACpF,IAAI,aAAa,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAC9C,QAAQ,CAAC,oBAAoB,CAC3B,UAAU,EACV,IAAI,EACJ,+DAA+D,CAChE,CAAC;gBAEF,OAAO,oBAAE,CAAC,OAAO,CAAC,uBAAuB,CAAC,SAAS,EAAE,aAAa,CAAC,CAAC;YACtE,CAAC;YAED,QAAQ,CAAC,oBAAoB,CAC3B,UAAU,EACV,IAAI,EACJ,8DAA8D,CAC/D,CAAC;YAEF,OAAO,oBAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,oBAAE,CAAC,UAAU,CAAC,aAAa,CAAC,CAAC;QACvE,CAAC;QACD,KAAK,QAAQ;YACX,QAAQ,CAAC,oBAAoB,CAC3B,UAAU,EACV,IAAI,EACJ,oDAAoD,CACrD,CAAC;YAEF,OAAO,oBAAE,CAAC,OAAO,CAAC,sBAAsB,CACtC,SAAS,EACT,EAAE,EACF,oBAAE,CAAC,OAAO,CAAC,qBAAqB,CAAC,oBAAE,CAAC,UAAU,CAAC,WAAW,CAAC,CAC5D,CAAC;IACN,CAAC;IAED,OAAO,IAAI,CAAC;AACd,CAAC"}
|
||||
Reference in New Issue
Block a user