Skip to content

Commit 58474ec

Browse files
committed
feat(@schematics/angular): introduce initial jasmine-to-vitest unit test refactor schematic
This commit introduces the base infrastructure for an experimental jasmine-to-vitest refactoring schematic and the initial set of transformers for lifecycle functions. The base infrastructure includes the main schematic entry point, the AST transformer driver, and various utilities for AST manipulation, validation, and reporting. The lifecycle transformers handle: - fdescribe/fit -> describe.only/it.only - xdescribe/xit -> describe.skip/it.skip - pending() -> it.skip() - Asynchronous tests using the 'done' callback are converted to 'async/await'. Usage: ng generate jasmine-to-vitest [--project <project-name>]
1 parent 5389951 commit 58474ec

File tree

13 files changed

+1175
-1
lines changed

13 files changed

+1175
-1
lines changed

packages/schematics/angular/BUILD.bazel

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,10 @@ ALL_SCHEMA_TARGETS = [
2020
x.replace("/", "_").replace("-", "_").replace(".json", ""),
2121
)
2222
for x in glob(
23-
include = ["*/schema.json"],
23+
include = [
24+
"*/schema.json",
25+
"refactor/*/schema.json",
26+
],
2427
exclude = [
2528
# NB: we need to exclude the nested node_modules that is laid out by yarn workspaces
2629
"node_modules/**",
@@ -55,6 +58,7 @@ RUNTIME_ASSETS = [
5558
"*/type-files/**/*",
5659
"*/functional-files/**/*",
5760
"*/class-files/**/*",
61+
"refactor/*/schema.json",
5862
],
5963
exclude = [
6064
# NB: we need to exclude the nested node_modules that is laid out by yarn workspaces
@@ -123,6 +127,7 @@ ts_project(
123127
":node_modules/jsonc-parser",
124128
"//:node_modules/@types/jasmine",
125129
"//:node_modules/@types/node",
130+
"//:node_modules/prettier",
126131
"//packages/schematics/angular/third_party/github.com/Microsoft/TypeScript",
127132
],
128133
)

packages/schematics/angular/collection.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,12 @@
143143
"hidden": true,
144144
"private": true,
145145
"description": "[INTERNAL] Adds tailwind to a project. Intended for use for ng new/add."
146+
},
147+
"jasmine-to-vitest": {
148+
"factory": "./refactor/jasmine-vitest",
149+
"schema": "./refactor/jasmine-vitest/schema.json",
150+
"description": "[EXPERIMENTAL] Refactors Jasmine tests to use Vitest APIs.",
151+
"hidden": true
146152
}
147153
}
148154
}
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import {
10+
DirEntry,
11+
Rule,
12+
SchematicContext,
13+
SchematicsException,
14+
Tree,
15+
} from '@angular-devkit/schematics';
16+
import { ProjectDefinition, getWorkspace } from '../../utility/workspace';
17+
import { Schema } from './schema';
18+
import { transformJasmineToVitest } from './test-file-transformer';
19+
import { RefactorReporter } from './utils/refactor-reporter';
20+
21+
async function getProjectRoot(tree: Tree, projectName: string | undefined): Promise<string> {
22+
const workspace = await getWorkspace(tree);
23+
24+
let project: ProjectDefinition | undefined;
25+
if (projectName) {
26+
project = workspace.projects.get(projectName);
27+
if (!project) {
28+
throw new SchematicsException(`Project "${projectName}" not found.`);
29+
}
30+
} else {
31+
if (workspace.projects.size === 1) {
32+
project = workspace.projects.values().next().value;
33+
} else {
34+
const projectNames = Array.from(workspace.projects.keys());
35+
throw new SchematicsException(
36+
`Multiple projects found: [${projectNames.join(', ')}]. Please specify a project name.`,
37+
);
38+
}
39+
}
40+
41+
if (!project) {
42+
// This case should theoretically not be hit due to the checks above, but it's good for type safety.
43+
throw new SchematicsException('Could not determine a project.');
44+
}
45+
46+
return project.root;
47+
}
48+
49+
const DIRECTORIES_TO_SKIP = new Set(['node_modules', '.git', 'dist', '.angular']);
50+
51+
function findTestFiles(directory: DirEntry, fileSuffix: string): string[] {
52+
const files: string[] = [];
53+
const stack: DirEntry[] = [directory];
54+
55+
let current: DirEntry | undefined;
56+
while ((current = stack.pop())) {
57+
for (const path of current.subfiles) {
58+
if (path.endsWith(fileSuffix)) {
59+
files.push(current.path + '/' + path);
60+
}
61+
}
62+
63+
for (const path of current.subdirs) {
64+
if (DIRECTORIES_TO_SKIP.has(path)) {
65+
continue;
66+
}
67+
stack.push(current.dir(path));
68+
}
69+
}
70+
71+
return files;
72+
}
73+
74+
export default function (options: Schema): Rule {
75+
return async (tree: Tree, context: SchematicContext) => {
76+
const reporter = new RefactorReporter(context.logger);
77+
const projectRoot = await getProjectRoot(tree, options.project);
78+
const fileSuffix = options.fileSuffix ?? '.spec.ts';
79+
80+
const files = findTestFiles(tree.getDir(projectRoot), fileSuffix);
81+
82+
if (files.length === 0) {
83+
throw new SchematicsException(
84+
`No files ending with '${fileSuffix}' found in project '${options.project}'.`,
85+
);
86+
}
87+
88+
for (const file of files) {
89+
reporter.incrementScannedFiles();
90+
const content = tree.readText(file);
91+
const newContent = transformJasmineToVitest(file, content, reporter);
92+
93+
if (content !== newContent) {
94+
tree.overwrite(file, newContent);
95+
reporter.incrementTransformedFiles();
96+
}
97+
}
98+
99+
reporter.printSummary(options.verbose);
100+
};
101+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
{
2+
"$schema": "http://json-schema.org/draft-07/schema",
3+
"$id": "SchematicsAngularJasmineToVitest",
4+
"title": "Angular Jasmine to Vitest Schematic",
5+
"type": "object",
6+
"description": "Refactors a Jasmine test file to use Vitest.",
7+
"properties": {
8+
"fileSuffix": {
9+
"type": "string",
10+
"description": "The file suffix to identify test files (e.g., '.spec.ts', '.test.ts').",
11+
"default": ".spec.ts"
12+
},
13+
"project": {
14+
"type": "string",
15+
"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.",
16+
"$default": {
17+
"$source": "projectName"
18+
}
19+
},
20+
"verbose": {
21+
"type": "boolean",
22+
"description": "Enable verbose logging to see detailed information about the transformations being applied.",
23+
"default": false
24+
}
25+
}
26+
}
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import ts from '../../third_party/github.com/Microsoft/TypeScript/lib/typescript';
10+
import {
11+
transformDoneCallback,
12+
transformFocusedAndSkippedTests,
13+
transformPending,
14+
} from './transformers/jasmine-lifecycle';
15+
import { RefactorContext } from './utils/refactor-context';
16+
import { RefactorReporter } from './utils/refactor-reporter';
17+
18+
/**
19+
* Transforms a string of Jasmine test code to Vitest test code.
20+
* This is the main entry point for the transformation.
21+
* @param content The source code to transform.
22+
* @param reporter The reporter to track TODOs.
23+
* @returns The transformed code.
24+
*/
25+
export function transformJasmineToVitest(
26+
filePath: string,
27+
content: string,
28+
reporter: RefactorReporter,
29+
): string {
30+
const sourceFile = ts.createSourceFile(
31+
filePath,
32+
content,
33+
ts.ScriptTarget.Latest,
34+
true,
35+
ts.ScriptKind.TS,
36+
);
37+
38+
const transformer: ts.TransformerFactory<ts.SourceFile> = (context) => {
39+
const refactorCtx: RefactorContext = {
40+
sourceFile,
41+
reporter,
42+
tsContext: context,
43+
};
44+
45+
const visitor: ts.Visitor = (node) => {
46+
let transformedNode: ts.Node | readonly ts.Node[] = node;
47+
48+
// Transform the node itself based on its type
49+
if (ts.isCallExpression(transformedNode)) {
50+
const transformations = [
51+
transformFocusedAndSkippedTests,
52+
transformPending,
53+
transformDoneCallback,
54+
];
55+
56+
for (const transformer of transformations) {
57+
transformedNode = transformer(transformedNode, refactorCtx);
58+
}
59+
}
60+
61+
// Visit the children of the node to ensure they are transformed
62+
if (Array.isArray(transformedNode)) {
63+
return transformedNode.map((node) => ts.visitEachChild(node, visitor, context));
64+
} else {
65+
return ts.visitEachChild(transformedNode, visitor, context);
66+
}
67+
};
68+
69+
return (node) => ts.visitNode(node, visitor) as ts.SourceFile;
70+
};
71+
72+
const result = ts.transform(sourceFile, [transformer]);
73+
if (result.transformed[0] === sourceFile) {
74+
return content;
75+
}
76+
77+
const printer = ts.createPrinter();
78+
79+
return printer.printFile(result.transformed[0]);
80+
}

0 commit comments

Comments
 (0)