Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/schematics/angular/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ ALL_SCHEMA_TARGETS = [
x.replace("/", "_").replace("-", "_").replace(".json", ""),
)
for x in glob(
include = ["*/schema.json"],
include = [
"*/schema.json",
"refactor/*/schema.json",
],
exclude = [
# NB: we need to exclude the nested node_modules that is laid out by yarn workspaces
"node_modules/**",
Expand Down Expand Up @@ -55,6 +58,7 @@ RUNTIME_ASSETS = [
"*/type-files/**/*",
"*/functional-files/**/*",
"*/class-files/**/*",
"refactor/*/schema.json",
],
exclude = [
# NB: we need to exclude the nested node_modules that is laid out by yarn workspaces
Expand Down Expand Up @@ -123,6 +127,7 @@ ts_project(
":node_modules/jsonc-parser",
"//:node_modules/@types/jasmine",
"//:node_modules/@types/node",
"//:node_modules/prettier",
"//packages/schematics/angular/third_party/github.com/Microsoft/TypeScript",
],
)
Expand Down
6 changes: 6 additions & 0 deletions packages/schematics/angular/collection.json
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,12 @@
"hidden": true,
"private": true,
"description": "[INTERNAL] Adds tailwind to a project. Intended for use for ng new/add."
},
"jasmine-to-vitest": {
"factory": "./refactor/jasmine-vitest",
"schema": "./refactor/jasmine-vitest/schema.json",
"description": "[EXPERIMENTAL] Refactors Jasmine tests to use Vitest APIs.",
"hidden": true
}
}
}
101 changes: 101 additions & 0 deletions packages/schematics/angular/refactor/jasmine-vitest/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/**
* @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
*/

import {
DirEntry,
Rule,
SchematicContext,
SchematicsException,
Tree,
} from '@angular-devkit/schematics';
import { ProjectDefinition, getWorkspace } from '../../utility/workspace';
import { Schema } from './schema';
import { transformJasmineToVitest } from './test-file-transformer';
import { RefactorReporter } from './utils/refactor-reporter';

async function getProjectRoot(tree: Tree, projectName: string | undefined): Promise<string> {
const workspace = await getWorkspace(tree);

let project: ProjectDefinition | undefined;
if (projectName) {
project = workspace.projects.get(projectName);
if (!project) {
throw new SchematicsException(`Project "${projectName}" not found.`);
}
} else {
if (workspace.projects.size === 1) {
project = workspace.projects.values().next().value;
} else {
const projectNames = Array.from(workspace.projects.keys());
throw new SchematicsException(
`Multiple projects found: [${projectNames.join(', ')}]. Please specify a project name.`,
);
}
}

if (!project) {
// This case should theoretically not be hit due to the checks above, but it's good for type safety.
throw new SchematicsException('Could not determine a project.');
}

return project.root;
}

const DIRECTORIES_TO_SKIP = new Set(['node_modules', '.git', 'dist', '.angular']);

function findTestFiles(directory: DirEntry, fileSuffix: string): string[] {
const files: string[] = [];
const stack: DirEntry[] = [directory];

let current: DirEntry | undefined;
while ((current = stack.pop())) {
for (const path of current.subfiles) {
if (path.endsWith(fileSuffix)) {
files.push(current.path + '/' + path);
}
}

for (const path of current.subdirs) {
if (DIRECTORIES_TO_SKIP.has(path)) {
continue;
}
stack.push(current.dir(path));
}
}

return files;
}

export default function (options: Schema): Rule {
return async (tree: Tree, context: SchematicContext) => {
const reporter = new RefactorReporter(context.logger);
const projectRoot = await getProjectRoot(tree, options.project);
const fileSuffix = options.fileSuffix ?? '.spec.ts';

const files = findTestFiles(tree.getDir(projectRoot), fileSuffix);

if (files.length === 0) {
throw new SchematicsException(
`No files ending with '${fileSuffix}' found in project '${options.project}'.`,
);
}

for (const file of files) {
reporter.incrementScannedFiles();
const content = tree.readText(file);
const newContent = transformJasmineToVitest(file, content, reporter);

if (content !== newContent) {
tree.overwrite(file, newContent);
reporter.incrementTransformedFiles();
}
}

reporter.printSummary(options.verbose);
};
}
26 changes: 26 additions & 0 deletions packages/schematics/angular/refactor/jasmine-vitest/schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "SchematicsAngularJasmineToVitest",
"title": "Angular Jasmine to Vitest Schematic",
"type": "object",
"description": "Refactors a Jasmine test file to use Vitest.",
"properties": {
"fileSuffix": {
"type": "string",
"description": "The file suffix to identify test files (e.g., '.spec.ts', '.test.ts').",
"default": ".spec.ts"
},
"project": {
"type": "string",
"description": "The name of the project where the tests should be refactored. If not specified, the CLI will determine the project from the current directory.",
"$default": {
"$source": "projectName"
}
},
"verbose": {
"type": "boolean",
"description": "Enable verbose logging to see detailed information about the transformations being applied.",
"default": false
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/**
* @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
*/

import ts from '../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
import {
transformDoneCallback,
transformFocusedAndSkippedTests,
transformPending,
} from './transformers/jasmine-lifecycle';
import { RefactorContext } from './utils/refactor-context';
import { RefactorReporter } from './utils/refactor-reporter';

/**
* Transforms a string of Jasmine test code to Vitest test code.
* This is the main entry point for the transformation.
* @param content The source code to transform.
* @param reporter The reporter to track TODOs.
* @returns The transformed code.
*/
export function transformJasmineToVitest(
filePath: string,
content: string,
reporter: RefactorReporter,
): string {
const sourceFile = ts.createSourceFile(
filePath,
content,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TS,
);

const transformer: ts.TransformerFactory<ts.SourceFile> = (context) => {
const refactorCtx: RefactorContext = {
sourceFile,
reporter,
tsContext: context,
};

const visitor: ts.Visitor = (node) => {
let transformedNode: ts.Node | readonly ts.Node[] = node;

// Transform the node itself based on its type
if (ts.isCallExpression(transformedNode)) {
const transformations = [
transformFocusedAndSkippedTests,
transformPending,
transformDoneCallback,
];

for (const transformer of transformations) {
transformedNode = transformer(transformedNode, refactorCtx);
}
}

// Visit the children of the node to ensure they are transformed
if (Array.isArray(transformedNode)) {
return transformedNode.map((node) => ts.visitEachChild(node, visitor, context));
} else {
return ts.visitEachChild(transformedNode, visitor, context);
}
};

return (node) => ts.visitNode(node, visitor) as ts.SourceFile;
};

const result = ts.transform(sourceFile, [transformer]);
if (result.transformed[0] === sourceFile) {
return content;
}

const printer = ts.createPrinter();

return printer.printFile(result.transformed[0]);
}
Loading