Skip to content

feat(@schematics/angular): add migration to remove default Karma configurations #30896

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 13, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,15 @@ export function analyzeKarmaConfig(content: string): KarmaConfigAnalysis {
}
case ts.SyntaxKind.PropertyAccessExpression: {
const propAccessExpr = node as ts.PropertyAccessExpression;

// Handle config constants like `config.LOG_INFO`
if (
ts.isIdentifier(propAccessExpr.expression) &&
propAccessExpr.expression.text === 'config'
) {
return `config.${propAccessExpr.name.text}`;
}

const value = extractValue(propAccessExpr.expression);
if (isRequireInfo(value)) {
const currentExport = value.export
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ describe('Karma Config Analyzer', () => {
expect(dirInfo.isCall).toBe(true);
expect(dirInfo.arguments as unknown).toEqual(['__dirname', './coverage/test-project']);

// config.LOG_INFO is a variable, so it should be flagged as unsupported
expect(hasUnsupportedValues).toBe(true);
expect(settings.get('logLevel') as unknown).toBe('config.LOG_INFO');
expect(hasUnsupportedValues).toBe(false);
});

it('should return an empty map for an empty config file', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,33 @@ import { isDeepStrictEqual } from 'node:util';
import { relativePathToWorkspaceRoot } from '../../utility/paths';
import { KarmaConfigAnalysis, KarmaConfigValue, analyzeKarmaConfig } from './karma-config-analyzer';

/**
* Represents the difference between two Karma configurations.
*/
export interface KarmaConfigDiff {
/** A map of settings that were added in the project's configuration. */
added: Map<string, KarmaConfigValue>;

/** A map of settings that were removed from the project's configuration. */
removed: Map<string, KarmaConfigValue>;

/** A map of settings that were modified between the two configurations. */
modified: Map<string, { projectValue: KarmaConfigValue; defaultValue: KarmaConfigValue }>;

/** A boolean indicating if the comparison is reliable (i.e., no unsupported values were found). */
isReliable: boolean;
}

/**
* Generates the default Karma configuration file content as a string.
* @param relativePathToWorkspaceRoot The relative path from the project root to the workspace root.
* @param folderName The name of the project folder.
* @param relativePathToWorkspaceRoot The relative path from the Karma config file to the workspace root.
* @param projectName The name of the project.
* @param needDevkitPlugin A boolean indicating if the devkit plugin is needed.
* @returns The content of the default `karma.conf.js` file.
*/
export async function generateDefaultKarmaConfig(
relativePathToWorkspaceRoot: string,
folderName: string,
projectName: string,
needDevkitPlugin: boolean,
): Promise<string> {
const templatePath = path.join(__dirname, '../../config/files/karma.conf.js.template');
Expand All @@ -40,7 +50,7 @@ export async function generateDefaultKarmaConfig(
/<%= relativePathToWorkspaceRoot %>/g,
path.normalize(relativePathToWorkspaceRoot).replace(/\\/g, '/'),
)
.replace(/<%= folderName %>/g, folderName);
.replace(/<%= folderName %>/g, projectName);

const devkitPluginRegex = /<% if \(needDevkitPlugin\) { %>(.*?)<% } %>/gs;
const replacement = needDevkitPlugin ? '$1' : '';
Expand All @@ -52,8 +62,8 @@ export async function generateDefaultKarmaConfig(
/**
* Compares two Karma configuration analyses and returns the difference.
* @param projectAnalysis The analysis of the project's configuration.
* @param defaultAnalysis The analysis of the default configuration.
* @returns A diff object representing the changes.
* @param defaultAnalysis The analysis of the default configuration to compare against.
* @returns A diff object representing the changes between the two configurations.
*/
export function compareKarmaConfigs(
projectAnalysis: KarmaConfigAnalysis,
Expand Down Expand Up @@ -93,8 +103,8 @@ export function compareKarmaConfigs(

/**
* Checks if there are any differences in the provided Karma configuration diff.
* @param diff The Karma configuration diff object.
* @returns True if there are any differences, false otherwise.
* @param diff The Karma configuration diff object to check.
* @returns True if there are any differences; false otherwise.
*/
export function hasDifferences(diff: KarmaConfigDiff): boolean {
return diff.added.size > 0 || diff.removed.size > 0 || diff.modified.size > 0;
Expand All @@ -103,41 +113,46 @@ export function hasDifferences(diff: KarmaConfigDiff): boolean {
/**
* Compares a project's Karma configuration with the default configuration.
* @param projectConfigContent The content of the project's `karma.conf.js` file.
* @param projectRoot The root of the project's project.
* @param needDevkitPlugin A boolean indicating if the devkit plugin is needed.
* @param projectRoot The root directory of the project.
* @param needDevkitPlugin A boolean indicating if the devkit plugin is needed for the default config.
* @param karmaConfigPath The path to the Karma configuration file, used to resolve relative paths.
* @returns A diff object representing the changes.
*/
export async function compareKarmaConfigToDefault(
projectConfigContent: string,
projectRoot: string,
needDevkitPlugin: boolean,
karmaConfigPath?: string,
): Promise<KarmaConfigDiff>;

/**
* Compares a project's Karma configuration with the default configuration.
* @param projectAnalysis The analysis of the project's configuration.
* @param projectRoot The root of the project's project.
* @param needDevkitPlugin A boolean indicating if the devkit plugin is needed.
* @param projectRoot The root directory of the project.
* @param needDevkitPlugin A boolean indicating if the devkit plugin is needed for the default config.
* @param karmaConfigPath The path to the Karma configuration file, used to resolve relative paths.
* @returns A diff object representing the changes.
*/
export async function compareKarmaConfigToDefault(
projectAnalysis: KarmaConfigAnalysis,
projectRoot: string,
needDevkitPlugin: boolean,
karmaConfigPath?: string,
): Promise<KarmaConfigDiff>;

export async function compareKarmaConfigToDefault(
projectConfigOrAnalysis: string | KarmaConfigAnalysis,
projectRoot: string,
needDevkitPlugin: boolean,
karmaConfigPath?: string,
): Promise<KarmaConfigDiff> {
const projectAnalysis =
typeof projectConfigOrAnalysis === 'string'
? analyzeKarmaConfig(projectConfigOrAnalysis)
: projectConfigOrAnalysis;

const defaultContent = await generateDefaultKarmaConfig(
relativePathToWorkspaceRoot(projectRoot),
relativePathToWorkspaceRoot(karmaConfigPath ? path.dirname(karmaConfigPath) : projectRoot),
path.basename(projectRoot),
needDevkitPlugin,
);
Expand Down
74 changes: 74 additions & 0 deletions packages/schematics/angular/migrations/karma/migration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* @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 type { Rule, Tree } from '@angular-devkit/schematics';
import { allTargetOptions, updateWorkspace } from '../../utility/workspace';
import { Builders } from '../../utility/workspace-models';
import { analyzeKarmaConfig } from './karma-config-analyzer';
import { compareKarmaConfigToDefault, hasDifferences } from './karma-config-comparer';

function updateProjects(tree: Tree): Rule {
return updateWorkspace(async (workspace) => {
const removableKarmaConfigs = new Map<string, boolean>();

for (const [, project] of workspace.projects) {
for (const [, target] of project.targets) {
let needDevkitPlugin = false;
switch (target.builder) {
case Builders.Karma:
needDevkitPlugin = true;
break;
case Builders.BuildKarma:
break;
default:
continue;
}

for (const [, options] of allTargetOptions(target, false)) {
const karmaConfig = options['karmaConfig'];
if (typeof karmaConfig !== 'string') {
continue;
}

let isRemovable = removableKarmaConfigs.get(karmaConfig);
if (isRemovable === undefined && tree.exists(karmaConfig)) {
const content = tree.readText(karmaConfig);
const analysis = analyzeKarmaConfig(content);

if (analysis.hasUnsupportedValues) {
// Cannot safely determine if the file is removable.
isRemovable = false;
} else {
const diff = await compareKarmaConfigToDefault(
analysis,
project.root,
needDevkitPlugin,
karmaConfig,
);
isRemovable = !hasDifferences(diff) && diff.isReliable;
}

removableKarmaConfigs.set(karmaConfig, isRemovable);

if (isRemovable) {
tree.delete(karmaConfig);
}
}

if (isRemovable) {
delete options['karmaConfig'];
}
}
}
}
});
}

export default function (): Rule {
return updateProjects;
}
Loading