Skip to content

Commit 06ccbf3

Browse files
committed
feat(@schematics/angular): add migrate-karma-to-vitest update migration
Migrate projects using the Karma unit-test builder to the new @angular/build:unit-test builder with Vitest. This migration automatically updates target builders, translates builder options (such as coverage and browsers format), moves custom build options to dedicated configurations to prevent loss of custom settings, cleans up default configuration files, and installs required Vitest runner packages.
1 parent 7fbc715 commit 06ccbf3

File tree

4 files changed

+415
-0
lines changed

4 files changed

+415
-0
lines changed
Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
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 type { json } from '@angular-devkit/core';
10+
import { Rule, SchematicContext, Tree, chain } from '@angular-devkit/schematics';
11+
import { DependencyType, ExistingBehavior, addDependency } from '../../utility/dependency';
12+
import { latestVersions } from '../../utility/latest-versions';
13+
import { allTargetOptions, updateWorkspace } from '../../utility/workspace';
14+
import { Builders } from '../../utility/workspace-models';
15+
import { analyzeKarmaConfig } from '../karma/karma-config-analyzer';
16+
import { compareKarmaConfigToDefault, hasDifferences } from '../karma/karma-config-comparer';
17+
18+
function updateProjects(tree: Tree, context: SchematicContext): Rule {
19+
return updateWorkspace(async (workspace) => {
20+
let hasMigratedAny = false;
21+
let needsCoverage = false;
22+
const removableKarmaConfigs = new Map<string, boolean>();
23+
24+
for (const [projectName, project] of workspace.projects) {
25+
// Find the test target to migrate
26+
const testTarget = project.targets.get('test');
27+
if (!testTarget) {
28+
continue;
29+
}
30+
31+
let isKarma = false;
32+
let needDevkitPlugin = false;
33+
// Check if target uses legacy Karma builders
34+
switch (testTarget.builder) {
35+
case Builders.Karma:
36+
isKarma = true;
37+
needDevkitPlugin = true;
38+
break;
39+
case Builders.BuildKarma:
40+
isKarma = true;
41+
break;
42+
}
43+
44+
if (!isKarma) {
45+
continue;
46+
}
47+
48+
// Store custom build options to move to a new build configuration if needed
49+
// Match Karma behavior where AOT was disabled by default
50+
const customBuildOptions: Record<string, json.JsonValue | undefined> = {
51+
aot: false,
52+
optimization: false,
53+
extractLicenses: false,
54+
};
55+
// List of build options that are supported by the new unit-test builder
56+
const buildOptionsKeys = [
57+
'assets',
58+
'styles',
59+
'scripts',
60+
'polyfills',
61+
'inlineStyleLanguage',
62+
'stylePreprocessorOptions',
63+
'externalDependencies',
64+
'loader',
65+
'define',
66+
'fileReplacements',
67+
'webWorkerTsConfig',
68+
'aot',
69+
];
70+
71+
for (const [, options] of allTargetOptions(testTarget, false)) {
72+
// Collect custom build options
73+
for (const key of buildOptionsKeys) {
74+
if (options[key] !== undefined) {
75+
customBuildOptions[key] = options[key];
76+
delete options[key];
77+
}
78+
}
79+
80+
// Map Karma options to Unit-Test options
81+
if (options['codeCoverage'] !== undefined) {
82+
options['coverage'] = options['codeCoverage'];
83+
delete options['codeCoverage'];
84+
}
85+
86+
if (options['codeCoverageExclude'] !== undefined) {
87+
options['coverageExclude'] = options['codeCoverageExclude'];
88+
delete options['codeCoverageExclude'];
89+
}
90+
91+
if (options['coverage'] === true || options['coverageExclude'] !== undefined) {
92+
needsCoverage = true;
93+
}
94+
95+
if (options['sourceMap'] !== undefined) {
96+
context.logger.info(
97+
`Project "${projectName}" has "sourceMap" set for tests. ` +
98+
`In unit-test builder with Vitest, source maps are always enabled. The option has been removed.`,
99+
);
100+
delete options['sourceMap'];
101+
}
102+
103+
// Convert browser list to array format if it is a comma-separated string
104+
const browsers = options['browsers'];
105+
if (typeof browsers === 'string') {
106+
options['browsers'] = browsers.split(',').map((b) => b.trim());
107+
} else if (browsers === false) {
108+
options['browsers'] = [];
109+
}
110+
111+
// Check if the karma configuration file can be safely removed
112+
const karmaConfig = options['karmaConfig'];
113+
if (typeof karmaConfig === 'string') {
114+
let isRemovable = removableKarmaConfigs.get(karmaConfig);
115+
if (isRemovable === undefined && tree.exists(karmaConfig)) {
116+
const content = tree.readText(karmaConfig);
117+
const analysis = analyzeKarmaConfig(content);
118+
119+
if (analysis.hasUnsupportedValues) {
120+
isRemovable = false;
121+
} else {
122+
const diff = await compareKarmaConfigToDefault(
123+
analysis,
124+
projectName,
125+
karmaConfig,
126+
needDevkitPlugin,
127+
);
128+
isRemovable = !hasDifferences(diff) && diff.isReliable;
129+
}
130+
removableKarmaConfigs.set(karmaConfig, isRemovable);
131+
}
132+
133+
if (isRemovable) {
134+
tree.delete(karmaConfig);
135+
} else {
136+
context.logger.warn(
137+
`Project "${projectName}" uses a custom Karma configuration file "${karmaConfig}". ` +
138+
`Tests have been migrated to use Vitest, but you may need to manually migrate custom settings ` +
139+
`from this Karma config to a Vitest config (e.g. vitest.config.ts).`,
140+
);
141+
}
142+
}
143+
144+
// Map the main entry file to the setupFiles of the unit-test builder
145+
const mainFile = options['main'];
146+
if (typeof mainFile === 'string') {
147+
options['setupFiles'] = [...((options['setupFiles'] as string[]) || []), mainFile];
148+
149+
context.logger.info(
150+
`Project "${projectName}" uses a "main" entry file for tests: "${mainFile}". ` +
151+
`This has been mapped to the unit-test builder "setupFiles" array. ` +
152+
`Please ensure you remove any TestBed.initTestEnvironment calls from this file ` +
153+
`as the builder now handles test environment initialization automatically.`,
154+
);
155+
}
156+
delete options['main'];
157+
}
158+
159+
// If we have custom build options, create a testing configuration
160+
if (Object.keys(customBuildOptions).length > 0) {
161+
const buildTarget = project.targets.get('build');
162+
if (buildTarget) {
163+
buildTarget.configurations ??= {};
164+
165+
let configName = 'testing';
166+
if (buildTarget.configurations[configName]) {
167+
let counter = 1;
168+
while (buildTarget.configurations[`${configName}-${counter}`]) {
169+
counter++;
170+
}
171+
configName = `${configName}-${counter}`;
172+
}
173+
174+
buildTarget.configurations[configName] = { ...customBuildOptions };
175+
176+
testTarget.options ??= {};
177+
testTarget.options['buildTarget'] = `:build:${configName}`;
178+
}
179+
}
180+
181+
// Update builder
182+
testTarget.builder = '@angular/build:unit-test';
183+
testTarget.options ??= {};
184+
testTarget.options['runner'] = 'vitest';
185+
186+
hasMigratedAny = true;
187+
}
188+
189+
if (hasMigratedAny) {
190+
const rules = [
191+
addDependency('vitest', latestVersions['vitest'], {
192+
type: DependencyType.Dev,
193+
existing: ExistingBehavior.Skip,
194+
}),
195+
];
196+
197+
if (needsCoverage) {
198+
rules.push(
199+
addDependency('@vitest/coverage-v8', latestVersions['@vitest/coverage-v8'], {
200+
type: DependencyType.Dev,
201+
existing: ExistingBehavior.Skip,
202+
}),
203+
);
204+
}
205+
206+
return chain(rules);
207+
}
208+
});
209+
}
210+
211+
export default function (): Rule {
212+
return updateProjects;
213+
}

0 commit comments

Comments
 (0)