Skip to content

Commit 3060a3e

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 3060a3e

File tree

4 files changed

+698
-0
lines changed

4 files changed

+698
-0
lines changed
Lines changed: 388 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,388 @@
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 { KarmaConfigAnalysis, analyzeKarmaConfig } from '../karma/karma-config-analyzer';
16+
import { compareKarmaConfigToDefault, hasDifferences } from '../karma/karma-config-comparer';
17+
18+
const SUPPORTED_REPORTERS = new Set([
19+
'default',
20+
'verbose',
21+
'dots',
22+
'json',
23+
'junit',
24+
'tap',
25+
'tap-flat',
26+
'html',
27+
]);
28+
29+
function extractReporters(
30+
analysis: KarmaConfigAnalysis,
31+
options: Record<string, json.JsonValue | undefined>,
32+
projectName: string,
33+
context: SchematicContext,
34+
): void {
35+
const reporters = analysis.settings.get('reporters');
36+
if (Array.isArray(reporters)) {
37+
const mappedReporters: string[] = [];
38+
for (const r of reporters) {
39+
if (typeof r === 'string') {
40+
if (r === 'progress') {
41+
mappedReporters.push('default');
42+
} else if (r === 'kjhtml') {
43+
context.logger.warn(
44+
`Project "${projectName}" uses the "kjhtml" reporter. ` +
45+
`This has not been automatically mapped. ` +
46+
`For an interactive test UI in Vitest, consider setting the "ui" option to true in your test target options ` +
47+
`and installing "@vitest/ui".`,
48+
);
49+
} else if (SUPPORTED_REPORTERS.has(r)) {
50+
mappedReporters.push(r);
51+
} else {
52+
context.logger.warn(
53+
`Project "${projectName}" uses a custom Karma reporter "${r}". ` +
54+
`This reporter cannot be automatically mapped to Vitest. ` +
55+
`Please check the Vitest documentation for equivalent reporters.`,
56+
);
57+
}
58+
} else {
59+
context.logger.warn(
60+
`Project "${projectName}" has a non-string reporter in Karma config. ` +
61+
`This cannot be automatically mapped to Vitest.`,
62+
);
63+
}
64+
}
65+
if (mappedReporters.length > 0) {
66+
options['reporters'] = [...new Set(mappedReporters)];
67+
}
68+
}
69+
}
70+
71+
function extractCoverageSettings(
72+
analysis: KarmaConfigAnalysis,
73+
options: Record<string, json.JsonValue | undefined>,
74+
): void {
75+
const coverageReporter = analysis.settings.get('coverageReporter');
76+
if (typeof coverageReporter !== 'object' || coverageReporter === null) {
77+
return;
78+
}
79+
80+
// Extract coverage reporters
81+
const covReporters = (coverageReporter as Record<string, unknown>)['reporters'];
82+
if (Array.isArray(covReporters)) {
83+
const mappedCovReporters: string[] = [];
84+
for (const r of covReporters) {
85+
if (typeof r === 'object' && r !== null && 'type' in r) {
86+
const type = r['type'];
87+
if (typeof type === 'string') {
88+
mappedCovReporters.push(type);
89+
}
90+
} else if (typeof r === 'string') {
91+
mappedCovReporters.push(r);
92+
}
93+
}
94+
if (mappedCovReporters.length > 0) {
95+
options['coverageReporters'] = mappedCovReporters;
96+
}
97+
}
98+
99+
// Extract coverage thresholds
100+
const check = (coverageReporter as Record<string, unknown>)['check'];
101+
if (typeof check === 'object' && check !== null) {
102+
const global = (check as Record<string, unknown>)['global'];
103+
if (typeof global === 'object' && global !== null) {
104+
const thresholds: Record<string, number> = {};
105+
const keys = ['statements', 'branches', 'functions', 'lines'];
106+
for (const key of keys) {
107+
const value = (global as Record<string, unknown>)[key];
108+
if (typeof value === 'number') {
109+
thresholds[key] = value;
110+
}
111+
}
112+
if (Object.keys(thresholds).length > 0) {
113+
options['coverageThresholds'] = {
114+
...thresholds,
115+
perFile: false,
116+
};
117+
}
118+
}
119+
}
120+
}
121+
122+
async function processKarmaConfig(
123+
karmaConfig: string,
124+
options: Record<string, json.JsonValue | undefined>,
125+
projectName: string,
126+
context: SchematicContext,
127+
tree: Tree,
128+
removableKarmaConfigs: Map<string, boolean>,
129+
needDevkitPlugin: boolean,
130+
): Promise<void> {
131+
if (tree.exists(karmaConfig)) {
132+
const content = tree.readText(karmaConfig);
133+
const analysis = analyzeKarmaConfig(content);
134+
135+
extractReporters(analysis, options, projectName, context);
136+
extractCoverageSettings(analysis, options);
137+
138+
let isRemovable = removableKarmaConfigs.get(karmaConfig);
139+
if (isRemovable === undefined) {
140+
if (analysis.hasUnsupportedValues) {
141+
isRemovable = false;
142+
} else {
143+
const diff = await compareKarmaConfigToDefault(
144+
analysis,
145+
projectName,
146+
karmaConfig,
147+
needDevkitPlugin,
148+
);
149+
isRemovable = !hasDifferences(diff) && diff.isReliable;
150+
}
151+
removableKarmaConfigs.set(karmaConfig, isRemovable);
152+
}
153+
154+
if (isRemovable) {
155+
tree.delete(karmaConfig);
156+
} else {
157+
context.logger.warn(
158+
`Project "${projectName}" uses a custom Karma configuration file "${karmaConfig}". ` +
159+
`Tests have been migrated to use Vitest, but you may need to manually migrate custom settings ` +
160+
`from this Karma config to a Vitest config (e.g. vitest.config.ts).`,
161+
);
162+
}
163+
}
164+
delete options['karmaConfig'];
165+
}
166+
167+
async function processTestTargetOptions(
168+
testTarget: TargetDefinition,
169+
projectName: string,
170+
context: SchematicContext,
171+
tree: Tree,
172+
removableKarmaConfigs: Map<string, boolean>,
173+
customBuildOptions: Record<string, json.JsonValue | undefined>,
174+
needDevkitPlugin: boolean,
175+
): Promise<boolean> {
176+
let needsCoverage = false;
177+
const buildOptionsKeys = [
178+
'assets',
179+
'styles',
180+
'scripts',
181+
'polyfills',
182+
'inlineStyleLanguage',
183+
'stylePreprocessorOptions',
184+
'externalDependencies',
185+
'loader',
186+
'define',
187+
'fileReplacements',
188+
'webWorkerTsConfig',
189+
'aot',
190+
];
191+
192+
for (const [, options] of allTargetOptions(testTarget, false)) {
193+
// Collect custom build options
194+
for (const key of buildOptionsKeys) {
195+
if (options[key] !== undefined) {
196+
customBuildOptions[key] = options[key];
197+
delete options[key];
198+
}
199+
}
200+
201+
// Map Karma options to Unit-Test options
202+
if (options['codeCoverage'] !== undefined) {
203+
options['coverage'] = options['codeCoverage'];
204+
delete options['codeCoverage'];
205+
}
206+
207+
if (options['codeCoverageExclude'] !== undefined) {
208+
options['coverageExclude'] = options['codeCoverageExclude'];
209+
delete options['codeCoverageExclude'];
210+
}
211+
212+
if (options['coverage'] === true || options['coverageExclude'] !== undefined) {
213+
needsCoverage = true;
214+
}
215+
216+
if (options['sourceMap'] !== undefined) {
217+
context.logger.info(
218+
`Project "${projectName}" has "sourceMap" set for tests. ` +
219+
`In unit-test builder with Vitest, source maps are always enabled. The option has been removed.`,
220+
);
221+
delete options['sourceMap'];
222+
}
223+
224+
// Convert browser list to array format if it is a comma-separated string
225+
const browsers = options['browsers'];
226+
if (typeof browsers === 'string') {
227+
options['browsers'] = browsers.split(',').map((b) => b.trim());
228+
} else if (browsers === false) {
229+
options['browsers'] = [];
230+
}
231+
232+
// Check if the karma configuration file can be safely removed and extract settings
233+
const karmaConfig = options['karmaConfig'];
234+
if (typeof karmaConfig === 'string') {
235+
await processKarmaConfig(
236+
karmaConfig,
237+
options,
238+
projectName,
239+
context,
240+
tree,
241+
removableKarmaConfigs,
242+
needDevkitPlugin,
243+
);
244+
}
245+
246+
// Map the main entry file to the setupFiles of the unit-test builder
247+
const mainFile = options['main'];
248+
if (typeof mainFile === 'string') {
249+
options['setupFiles'] = [...((options['setupFiles'] as string[]) || []), mainFile];
250+
251+
context.logger.info(
252+
`Project "${projectName}" uses a "main" entry file for tests: "${mainFile}". ` +
253+
`This has been mapped to the unit-test builder "setupFiles" array. ` +
254+
`Please ensure you remove any TestBed.initTestEnvironment calls from this file ` +
255+
`as the builder now handles test environment initialization automatically.`,
256+
);
257+
}
258+
delete options['main'];
259+
}
260+
261+
return needsCoverage;
262+
}
263+
264+
function updateProjects(tree: Tree, context: SchematicContext): Rule {
265+
return updateWorkspace(async (workspace) => {
266+
let hasMigratedAny = false;
267+
let needsCoverage = false;
268+
const removableKarmaConfigs = new Map<string, boolean>();
269+
270+
for (const [projectName, project] of workspace.projects) {
271+
// Restrict to application types for now
272+
if (project.extensions.projectType !== 'application') {
273+
continue;
274+
}
275+
276+
// Find the test target to migrate
277+
const testTarget = project.targets.get('test');
278+
if (!testTarget) {
279+
continue;
280+
}
281+
282+
let isKarma = false;
283+
let needDevkitPlugin = false;
284+
// Check if target uses Karma builders
285+
switch (testTarget.builder) {
286+
case Builders.Karma:
287+
isKarma = true;
288+
needDevkitPlugin = true;
289+
break;
290+
case Builders.BuildKarma:
291+
isKarma = true;
292+
break;
293+
}
294+
295+
if (!isKarma) {
296+
continue;
297+
}
298+
299+
// Store custom build options to move to a new build configuration if needed
300+
// Match Karma behavior where AOT was disabled by default
301+
const customBuildOptions: Record<string, json.JsonValue | undefined> = {
302+
aot: false,
303+
optimization: false,
304+
extractLicenses: false,
305+
};
306+
307+
const projectNeedsCoverage = await processTestTargetOptions(
308+
testTarget,
309+
projectName,
310+
context,
311+
tree,
312+
removableKarmaConfigs,
313+
customBuildOptions,
314+
needDevkitPlugin,
315+
);
316+
317+
if (projectNeedsCoverage) {
318+
needsCoverage = true;
319+
}
320+
321+
// If we have custom build options, create a testing configuration
322+
if (Object.keys(customBuildOptions).length > 0) {
323+
const buildTarget = project.targets.get('build');
324+
if (buildTarget) {
325+
const baseOptions = buildTarget.options || {};
326+
const finalConfig: Record<string, json.JsonValue | undefined> = {};
327+
328+
// Omit options that already have the same value in the base build options.
329+
// Using JSON.stringify for a basic deep comparison of arrays and objects.
330+
for (const [key, value] of Object.entries(customBuildOptions)) {
331+
if (JSON.stringify(value) !== JSON.stringify(baseOptions[key])) {
332+
finalConfig[key] = value;
333+
}
334+
}
335+
336+
if (Object.keys(finalConfig).length > 0) {
337+
buildTarget.configurations ??= {};
338+
339+
let configName = 'testing';
340+
if (buildTarget.configurations[configName]) {
341+
let counter = 1;
342+
while (buildTarget.configurations[`${configName}-${counter}`]) {
343+
counter++;
344+
}
345+
configName = `${configName}-${counter}`;
346+
}
347+
348+
buildTarget.configurations[configName] = finalConfig;
349+
350+
testTarget.options ??= {};
351+
testTarget.options['buildTarget'] = `:build:${configName}`;
352+
}
353+
}
354+
}
355+
356+
// Update builder
357+
testTarget.builder = '@angular/build:unit-test';
358+
testTarget.options ??= {};
359+
testTarget.options['runner'] = 'vitest';
360+
361+
hasMigratedAny = true;
362+
}
363+
364+
if (hasMigratedAny) {
365+
const rules = [
366+
addDependency('vitest', latestVersions['vitest'], {
367+
type: DependencyType.Dev,
368+
existing: ExistingBehavior.Skip,
369+
}),
370+
];
371+
372+
if (needsCoverage) {
373+
rules.push(
374+
addDependency('@vitest/coverage-v8', latestVersions['@vitest/coverage-v8'], {
375+
type: DependencyType.Dev,
376+
existing: ExistingBehavior.Skip,
377+
}),
378+
);
379+
}
380+
381+
return chain(rules);
382+
}
383+
});
384+
}
385+
386+
export default function (): Rule {
387+
return updateProjects;
388+
}

0 commit comments

Comments
 (0)