Skip to content

Commit a79a8c0

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 a79a8c0

File tree

4 files changed

+486
-0
lines changed

4 files changed

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

0 commit comments

Comments
 (0)