From 960d0506a3aecd2f4eddd810ca6fd029676659d4 Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Mon, 4 Aug 2025 11:51:51 -0400 Subject: [PATCH] refactor(@schematics/angular): add Karma configuration analyzer and comparer Introduces a new utility for analyzing and comparing Karma configuration files. This is a foundational step for migrating from Karma to other testing frameworks like Jest and Vitest, as it allows the migration schematic to understand the user's existing setup. The new `analyzeKarmaConfig` function uses TypeScript's AST parser to safely extract settings from a `karma.conf.js` file. It can identify common patterns, including `require` calls, and flags configurations that are too complex for static analysis. The `compareKarmaConfigs` function provides the ability to diff a user's Karma configuration against a default template. This will be used to determine which custom settings need to be migrated. Known limitations of the analyzer: - It does not resolve variables or complex expressions. Any value that is not a literal (string, number, boolean, array, object) or a direct `require` call will be marked as an unsupported value. - It does not support Karma configuration files that use ES Modules (import/export syntax). --- .../migrations/karma/karma-config-analyzer.ts | 159 +++++++++ .../karma/karma-config-analyzer_spec.ts | 296 +++++++++++++++++ .../migrations/karma/karma-config-comparer.ts | 147 +++++++++ .../karma/karma-config-comparer_spec.ts | 307 ++++++++++++++++++ 4 files changed, 909 insertions(+) create mode 100644 packages/schematics/angular/migrations/karma/karma-config-analyzer.ts create mode 100644 packages/schematics/angular/migrations/karma/karma-config-analyzer_spec.ts create mode 100644 packages/schematics/angular/migrations/karma/karma-config-comparer.ts create mode 100644 packages/schematics/angular/migrations/karma/karma-config-comparer_spec.ts diff --git a/packages/schematics/angular/migrations/karma/karma-config-analyzer.ts b/packages/schematics/angular/migrations/karma/karma-config-analyzer.ts new file mode 100644 index 000000000000..0df221099568 --- /dev/null +++ b/packages/schematics/angular/migrations/karma/karma-config-analyzer.ts @@ -0,0 +1,159 @@ +/** + * @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 ts from '../../third_party/github.com/Microsoft/TypeScript/lib/typescript'; + +export interface RequireInfo { + module: string; + export?: string; + isCall?: boolean; + arguments?: KarmaConfigValue[]; +} + +export type KarmaConfigValue = + | string + | boolean + | number + | KarmaConfigValue[] + | { [key: string]: KarmaConfigValue } + | RequireInfo + | undefined; + +export interface KarmaConfigAnalysis { + settings: Map; + hasUnsupportedValues: boolean; +} + +function isRequireInfo(value: KarmaConfigValue): value is RequireInfo { + return typeof value === 'object' && value !== null && !Array.isArray(value) && 'module' in value; +} + +function isSupportedPropertyAssignment( + prop: ts.ObjectLiteralElementLike, +): prop is ts.PropertyAssignment & { name: ts.Identifier | ts.StringLiteral } { + return ( + ts.isPropertyAssignment(prop) && (ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name)) + ); +} + +/** + * Analyzes the content of a Karma configuration file to extract its settings. + * + * @param content The string content of the `karma.conf.js` file. + * @returns An object containing the configuration settings and a flag indicating if unsupported values were found. + */ +export function analyzeKarmaConfig(content: string): KarmaConfigAnalysis { + const sourceFile = ts.createSourceFile('karma.conf.js', content, ts.ScriptTarget.Latest, true); + const settings = new Map(); + let hasUnsupportedValues = false; + + function visit(node: ts.Node) { + // The Karma configuration is defined within a `config.set({ ... })` call. + if ( + ts.isCallExpression(node) && + ts.isPropertyAccessExpression(node.expression) && + node.expression.expression.getText(sourceFile) === 'config' && + node.expression.name.text === 'set' && + node.arguments.length === 1 && + ts.isObjectLiteralExpression(node.arguments[0]) + ) { + // We found `config.set`, now we extract the properties from the object literal. + for (const prop of node.arguments[0].properties) { + if (isSupportedPropertyAssignment(prop)) { + const key = prop.name.text; + const value = extractValue(prop.initializer); + settings.set(key, value); + } else { + hasUnsupportedValues = true; + } + } + } else { + ts.forEachChild(node, visit); + } + } + + function extractValue(node: ts.Expression): KarmaConfigValue { + switch (node.kind) { + case ts.SyntaxKind.StringLiteral: + return (node as ts.StringLiteral).text; + case ts.SyntaxKind.NumericLiteral: + return Number((node as ts.NumericLiteral).text); + case ts.SyntaxKind.TrueKeyword: + return true; + case ts.SyntaxKind.FalseKeyword: + return false; + case ts.SyntaxKind.Identifier: { + const identifier = (node as ts.Identifier).text; + if (identifier === '__dirname' || identifier === '__filename') { + return identifier; + } + break; + } + case ts.SyntaxKind.CallExpression: { + const callExpr = node as ts.CallExpression; + // Handle require('...') + if ( + ts.isIdentifier(callExpr.expression) && + callExpr.expression.text === 'require' && + callExpr.arguments.length === 1 && + ts.isStringLiteral(callExpr.arguments[0]) + ) { + return { module: callExpr.arguments[0].text }; + } + + // Handle calls on a require, e.g. require('path').join() + const calleeValue = extractValue(callExpr.expression); + if (isRequireInfo(calleeValue)) { + return { + ...calleeValue, + isCall: true, + arguments: callExpr.arguments.map(extractValue), + }; + } + break; + } + case ts.SyntaxKind.PropertyAccessExpression: { + const propAccessExpr = node as ts.PropertyAccessExpression; + const value = extractValue(propAccessExpr.expression); + if (isRequireInfo(value)) { + const currentExport = value.export + ? `${value.export}.${propAccessExpr.name.text}` + : propAccessExpr.name.text; + + return { ...value, export: currentExport }; + } + break; + } + case ts.SyntaxKind.ArrayLiteralExpression: + return (node as ts.ArrayLiteralExpression).elements.map(extractValue); + case ts.SyntaxKind.ObjectLiteralExpression: { + const obj: { [key: string]: KarmaConfigValue } = {}; + for (const prop of (node as ts.ObjectLiteralExpression).properties) { + if (isSupportedPropertyAssignment(prop)) { + // Recursively extract values for nested objects. + obj[prop.name.text] = extractValue(prop.initializer); + } else { + hasUnsupportedValues = true; + } + } + + return obj; + } + } + + // For complex expressions (like variables) that we don't need to resolve, + // we mark the analysis as potentially incomplete. + hasUnsupportedValues = true; + + return undefined; + } + + visit(sourceFile); + + return { settings, hasUnsupportedValues }; +} diff --git a/packages/schematics/angular/migrations/karma/karma-config-analyzer_spec.ts b/packages/schematics/angular/migrations/karma/karma-config-analyzer_spec.ts new file mode 100644 index 000000000000..51e3dd473a6b --- /dev/null +++ b/packages/schematics/angular/migrations/karma/karma-config-analyzer_spec.ts @@ -0,0 +1,296 @@ +/** + * @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 { RequireInfo, analyzeKarmaConfig } from './karma-config-analyzer'; +import { generateDefaultKarmaConfig } from './karma-config-comparer'; + +describe('Karma Config Analyzer', () => { + it('should parse a basic karma config file', () => { + const karmaConf = ` + module.exports = function (config) { + config.set({ + basePath: '', + frameworks: ['jasmine', '@angular-devkit/build-angular'], + plugins: [ + require('karma-jasmine'), + require('karma-chrome-launcher'), + require('karma-jasmine-html-reporter'), + require('karma-coverage'), + require('@angular-devkit/build-angular/plugins/karma'), + ], + client: { + clearContext: false, // leave Jasmine Spec Runner output visible in browser + }, + jasmineHtmlReporter: { + suppressAll: true, // removes the duplicated traces + }, + coverageReporter: { + dir: require('path').join(__dirname, './coverage/test-project'), + subdir: '.', + reporters: [{ type: 'html' }, { type: 'text-summary' }], + }, + reporters: ['progress', 'kjhtml'], + port: 9876, + colors: true, + logLevel: config.LOG_INFO, + autoWatch: true, + browsers: ['Chrome'], + singleRun: false, + restartOnFileChange: true, + }); + }; + `; + + const { settings, hasUnsupportedValues } = analyzeKarmaConfig(karmaConf); + + expect(settings.get('basePath') as unknown).toBe(''); + expect(settings.get('frameworks') as unknown).toEqual([ + 'jasmine', + '@angular-devkit/build-angular', + ]); + expect(settings.get('port') as unknown).toBe(9876); + expect(settings.get('autoWatch') as boolean).toBe(true); + expect(settings.get('singleRun') as boolean).toBe(false); + expect(settings.get('reporters') as unknown).toEqual(['progress', 'kjhtml']); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const plugins = settings.get('plugins') as any[]; + expect(plugins).toBeInstanceOf(Array); + expect(plugins.length).toBe(5); + expect(plugins[0]).toEqual({ module: 'karma-jasmine' }); + expect(plugins[4]).toEqual({ module: '@angular-devkit/build-angular/plugins/karma' }); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const coverageReporter = settings.get('coverageReporter') as any; + const dirInfo = coverageReporter.dir as RequireInfo; + expect(dirInfo.module).toBe('path'); + expect(dirInfo.export).toBe('join'); + 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); + }); + + it('should return an empty map for an empty config file', () => { + const { settings, hasUnsupportedValues } = analyzeKarmaConfig(''); + + expect(settings.size).toBe(0); + expect(hasUnsupportedValues).toBe(false); + }); + + it('should handle a config file with no config.set call', () => { + const karmaConf = ` + module.exports = function (config) { + // No config.set call + }; + `; + const { settings, hasUnsupportedValues } = analyzeKarmaConfig(karmaConf); + + expect(settings.size).toBe(0); + expect(hasUnsupportedValues).toBe(false); + }); + + it('should detect unsupported values like variables', () => { + const karmaConf = ` + const myBrowsers = ['Chrome', 'Firefox']; + module.exports = function (config) { + config.set({ + browsers: myBrowsers, + }); + }; + `; + const { settings, hasUnsupportedValues } = analyzeKarmaConfig(karmaConf); + + expect(settings.get('browsers')).toBeUndefined(); + expect(hasUnsupportedValues).toBe(true); + }); + + it('should correctly parse require with nested exports', () => { + const karmaConf = ` + module.exports = function (config) { + config.set({ + reporter: require('some-plugin').reporter.type, + }); + }; + `; + const { settings, hasUnsupportedValues } = analyzeKarmaConfig(karmaConf); + + const reporter = settings.get('reporter') as RequireInfo; + expect(reporter.module).toBe('some-plugin'); + expect(reporter.export).toBe('reporter.type'); + expect(hasUnsupportedValues).toBe(false); + }); + + it('should handle an array with mixed values', () => { + const karmaConf = ` + module.exports = function (config) { + config.set({ + plugins: [ + 'karma-jasmine', + require('karma-chrome-launcher'), + true, + ], + }); + }; + `; + const { settings, hasUnsupportedValues } = analyzeKarmaConfig(karmaConf); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const plugins = settings.get('plugins') as any[]; + expect(plugins).toEqual(['karma-jasmine', { module: 'karma-chrome-launcher' }, true]); + expect(hasUnsupportedValues).toBe(false); + }); + + it('should not report unsupported values when all values are literals or requires', () => { + const karmaConf = ` + module.exports = function (config) { + config.set({ + autoWatch: true, + browsers: ['Chrome'], + plugins: [require('karma-jasmine')], + }); + }; + `; + const { hasUnsupportedValues } = analyzeKarmaConfig(karmaConf); + + expect(hasUnsupportedValues).toBe(false); + }); + + it('should handle path.join with variables and flag as unsupported', () => { + const karmaConf = ` + const myPath = './coverage/test-project'; + module.exports = function (config) { + config.set({ + coverageReporter: { + dir: require('path').join(__dirname, myPath), + }, + }); + }; + `; + const { settings, hasUnsupportedValues } = analyzeKarmaConfig(karmaConf); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const coverageReporter = settings.get('coverageReporter') as any; + const dirInfo = coverageReporter.dir as RequireInfo; + expect(dirInfo.module).toBe('path'); + expect(dirInfo.export).toBe('join'); + expect(dirInfo.isCall).toBe(true); + expect(dirInfo.arguments as unknown).toEqual(['__dirname', undefined]); // myPath is a variable + expect(hasUnsupportedValues).toBe(true); + }); + + it('should correctly parse the default karma config template', async () => { + const defaultConfig = await generateDefaultKarmaConfig('..', 'test-project', true); + const { settings, hasUnsupportedValues } = analyzeKarmaConfig(defaultConfig); + + expect(hasUnsupportedValues).toBe(false); + expect(settings.get('basePath') as unknown).toBe(''); + expect(settings.get('frameworks') as unknown).toEqual([ + 'jasmine', + '@angular-devkit/build-angular', + ]); + expect(settings.get('plugins') as unknown).toEqual([ + { module: 'karma-jasmine' }, + { module: 'karma-chrome-launcher' }, + { module: 'karma-jasmine-html-reporter' }, + { module: 'karma-coverage' }, + { module: '@angular-devkit/build-angular/plugins/karma' }, + ]); + expect(settings.get('client') as unknown).toEqual({ + jasmine: {}, + }); + expect(settings.get('jasmineHtmlReporter') as unknown).toEqual({ + suppressAll: true, + }); + const coverageReporter = settings.get('coverageReporter') as { + dir: RequireInfo; + subdir: string; + reporters: { type: string }[]; + }; + expect(coverageReporter.dir.module).toBe('path'); + expect(coverageReporter.dir.export).toBe('join'); + expect(coverageReporter.dir.isCall).toBe(true); + expect(coverageReporter.dir.arguments as unknown).toEqual([ + '__dirname', + '../coverage/test-project', + ]); + expect(coverageReporter.subdir).toBe('.'); + expect(coverageReporter.reporters).toEqual([{ type: 'html' }, { type: 'text-summary' }]); + expect(settings.get('reporters') as unknown).toEqual(['progress', 'kjhtml']); + expect(settings.get('browsers') as unknown).toEqual(['Chrome']); + expect(settings.get('restartOnFileChange') as unknown).toBe(true); + }); + + it('should correctly parse require with property access and a call', () => { + const karmaConf = ` + module.exports = function (config) { + config.set({ + reporter: require('some-plugin').reporter.doSomething(), + }); + }; + `; + const { settings, hasUnsupportedValues } = analyzeKarmaConfig(karmaConf); + + const reporter: RequireInfo = settings.get('reporter') as RequireInfo; + expect(reporter.module).toBe('some-plugin'); + expect(reporter.export).toBe('reporter.doSomething'); + expect(reporter.isCall).toBe(true); + expect(reporter.arguments?.length).toBe(0); + expect(hasUnsupportedValues).toBe(false); + }); + + it('should flag require with a variable as unsupported', () => { + const karmaConf = ` + const myPlugin = 'karma-jasmine'; + module.exports = function (config) { + config.set({ + plugins: [require(myPlugin)], + }); + }; + `; + const { settings, hasUnsupportedValues } = analyzeKarmaConfig(karmaConf); + + const plugins = settings.get('plugins') as unknown[]; + expect(plugins.length).toBe(1); + expect(plugins[0]).toBeUndefined(); + expect(hasUnsupportedValues).toBe(true); + }); + + it('should flag object with spread assignment as unsupported', () => { + const karmaConf = ` + const otherSettings = { basePath: '' }; + module.exports = function (config) { + config.set({ + ...otherSettings, + port: 9876, + }); + }; + `; + const { settings, hasUnsupportedValues } = analyzeKarmaConfig(karmaConf); + + expect(settings.get('port') as unknown).toBe(9876); + expect(settings.has('basePath')).toBe(false); + expect(hasUnsupportedValues).toBe(true); + }); + + it('should flag property with computed name as unsupported', () => { + const karmaConf = ` + const myKey = 'port'; + module.exports = function (config) { + config.set({ + [myKey]: 9876, + }); + }; + `; + const { settings, hasUnsupportedValues } = analyzeKarmaConfig(karmaConf); + + expect(settings.size).toBe(0); + expect(hasUnsupportedValues).toBe(true); + }); +}); diff --git a/packages/schematics/angular/migrations/karma/karma-config-comparer.ts b/packages/schematics/angular/migrations/karma/karma-config-comparer.ts new file mode 100644 index 000000000000..f81bf691f3c8 --- /dev/null +++ b/packages/schematics/angular/migrations/karma/karma-config-comparer.ts @@ -0,0 +1,147 @@ +/** + * @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 { readFile } from 'node:fs/promises'; +import path from 'node:path/posix'; +import { isDeepStrictEqual } from 'node:util'; +import { relativePathToWorkspaceRoot } from '../../utility/paths'; +import { KarmaConfigAnalysis, KarmaConfigValue, analyzeKarmaConfig } from './karma-config-analyzer'; + +export interface KarmaConfigDiff { + added: Map; + removed: Map; + modified: Map; + 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 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, + needDevkitPlugin: boolean, +): Promise { + const templatePath = path.join(__dirname, '../../config/files/karma.conf.js.template'); + let template = await readFile(templatePath, 'utf-8'); + + // TODO: Replace this with the actual schematic templating logic. + template = template + .replace( + /<%= relativePathToWorkspaceRoot %>/g, + path.normalize(relativePathToWorkspaceRoot).replace(/\\/g, '/'), + ) + .replace(/<%= folderName %>/g, folderName); + + const devkitPluginRegex = /<% if \(needDevkitPlugin\) { %>(.*?)<% } %>/gs; + const replacement = needDevkitPlugin ? '$1' : ''; + template = template.replace(devkitPluginRegex, replacement); + + return template; +} + +/** + * 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. + */ +export function compareKarmaConfigs( + projectAnalysis: KarmaConfigAnalysis, + defaultAnalysis: KarmaConfigAnalysis, +): KarmaConfigDiff { + const added = new Map(); + const removed = new Map(); + const modified = new Map< + string, + { projectValue: KarmaConfigValue; defaultValue: KarmaConfigValue } + >(); + + const allKeys = new Set([...projectAnalysis.settings.keys(), ...defaultAnalysis.settings.keys()]); + + for (const key of allKeys) { + const projectValue = projectAnalysis.settings.get(key); + const defaultValue = defaultAnalysis.settings.get(key); + + if (projectValue !== undefined && defaultValue === undefined) { + added.set(key, projectValue); + } else if (projectValue === undefined && defaultValue !== undefined) { + removed.set(key, defaultValue); + } else if (projectValue !== undefined && defaultValue !== undefined) { + if (!isDeepStrictEqual(projectValue, defaultValue)) { + modified.set(key, { projectValue, defaultValue }); + } + } + } + + return { + added, + removed, + modified, + isReliable: !projectAnalysis.hasUnsupportedValues && !defaultAnalysis.hasUnsupportedValues, + }; +} + +/** + * 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. + */ +export function hasDifferences(diff: KarmaConfigDiff): boolean { + return diff.added.size > 0 || diff.removed.size > 0 || diff.modified.size > 0; +} + +/** + * 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. + * @returns A diff object representing the changes. + */ +export async function compareKarmaConfigToDefault( + projectConfigContent: string, + projectRoot: string, + needDevkitPlugin: boolean, +): Promise; + +/** + * 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. + * @returns A diff object representing the changes. + */ +export async function compareKarmaConfigToDefault( + projectAnalysis: KarmaConfigAnalysis, + projectRoot: string, + needDevkitPlugin: boolean, +): Promise; + +export async function compareKarmaConfigToDefault( + projectConfigOrAnalysis: string | KarmaConfigAnalysis, + projectRoot: string, + needDevkitPlugin: boolean, +): Promise { + const projectAnalysis = + typeof projectConfigOrAnalysis === 'string' + ? analyzeKarmaConfig(projectConfigOrAnalysis) + : projectConfigOrAnalysis; + + const defaultContent = await generateDefaultKarmaConfig( + relativePathToWorkspaceRoot(projectRoot), + path.basename(projectRoot), + needDevkitPlugin, + ); + const defaultAnalysis = analyzeKarmaConfig(defaultContent); + + return compareKarmaConfigs(projectAnalysis, defaultAnalysis); +} diff --git a/packages/schematics/angular/migrations/karma/karma-config-comparer_spec.ts b/packages/schematics/angular/migrations/karma/karma-config-comparer_spec.ts new file mode 100644 index 000000000000..fbd259a10c4c --- /dev/null +++ b/packages/schematics/angular/migrations/karma/karma-config-comparer_spec.ts @@ -0,0 +1,307 @@ +/** + * @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 { KarmaConfigAnalysis, KarmaConfigValue, RequireInfo } from './karma-config-analyzer'; +import { + compareKarmaConfigToDefault, + compareKarmaConfigs, + generateDefaultKarmaConfig, +} from './karma-config-comparer'; + +describe('Karma Config Comparer', () => { + describe('compareKarmaConfigs', () => { + it('should find no differences for identical configs', () => { + const projectAnalysis: KarmaConfigAnalysis = { + settings: new Map([['propA', 'valueA']]), + hasUnsupportedValues: false, + }; + const defaultAnalysis: KarmaConfigAnalysis = { + settings: new Map([['propA', 'valueA']]), + hasUnsupportedValues: false, + }; + + const diff = compareKarmaConfigs(projectAnalysis, defaultAnalysis); + + expect(diff.isReliable).toBe(true); + expect(diff.added.size).toBe(0); + expect(diff.removed.size).toBe(0); + expect(diff.modified.size).toBe(0); + }); + + it('should detect added properties', () => { + const projectAnalysis: KarmaConfigAnalysis = { + settings: new Map([ + ['propA', 'valueA'], + ['propB', 'valueB'], + ]), + hasUnsupportedValues: false, + }; + const defaultAnalysis: KarmaConfigAnalysis = { + settings: new Map([['propA', 'valueA']]), + hasUnsupportedValues: false, + }; + + const diff = compareKarmaConfigs(projectAnalysis, defaultAnalysis); + + expect(diff.isReliable).toBe(true); + expect(diff.added.size).toBe(1); + expect(diff.added.get('propB') as unknown).toBe('valueB'); + expect(diff.removed.size).toBe(0); + expect(diff.modified.size).toBe(0); + }); + + it('should detect removed properties', () => { + const projectAnalysis: KarmaConfigAnalysis = { + settings: new Map([['propA', 'valueA']]), + hasUnsupportedValues: false, + }; + const defaultAnalysis: KarmaConfigAnalysis = { + settings: new Map([ + ['propA', 'valueA'], + ['propB', 'valueB'], + ]), + hasUnsupportedValues: false, + }; + + const diff = compareKarmaConfigs(projectAnalysis, defaultAnalysis); + + expect(diff.isReliable).toBe(true); + expect(diff.added.size).toBe(0); + expect(diff.removed.size).toBe(1); + expect(diff.removed.get('propB') as unknown).toBe('valueB'); + expect(diff.modified.size).toBe(0); + }); + + it('should detect modified properties', () => { + const projectAnalysis: KarmaConfigAnalysis = { + settings: new Map([['propA', 'newValue']]), + hasUnsupportedValues: false, + }; + const defaultAnalysis: KarmaConfigAnalysis = { + settings: new Map([['propA', 'oldValue']]), + hasUnsupportedValues: false, + }; + + const diff = compareKarmaConfigs(projectAnalysis, defaultAnalysis); + + expect(diff.isReliable).toBe(true); + expect(diff.added.size).toBe(0); + expect(diff.removed.size).toBe(0); + expect(diff.modified.size).toBe(1); + const modifiedProp = diff.modified.get('propA'); + expect(modifiedProp?.projectValue as unknown).toBe('newValue'); + expect(modifiedProp?.defaultValue as unknown).toBe('oldValue'); + }); + + it('should handle a mix of added, removed, and modified properties', () => { + const projectAnalysis: KarmaConfigAnalysis = { + settings: new Map([ + ['propA', 'valueA'], // unchanged + ['propB', 'newValueB'], // modified + ['propC', 'valueC'], // added + ]), + hasUnsupportedValues: false, + }; + const defaultAnalysis: KarmaConfigAnalysis = { + settings: new Map([ + ['propA', 'valueA'], + ['propB', 'oldValueB'], + ['propD', 'valueD'], // removed + ]), + hasUnsupportedValues: false, + }; + + const diff = compareKarmaConfigs(projectAnalysis, defaultAnalysis); + + expect(diff.isReliable).toBe(true); + expect(diff.added.size).toBe(1); + expect(diff.added.get('propC') as unknown).toBe('valueC'); + expect(diff.removed.size).toBe(1); + expect(diff.removed.get('propD') as unknown).toBe('valueD'); + expect(diff.modified.size).toBe(1); + const modifiedPropB = diff.modified.get('propB'); + expect(modifiedPropB?.projectValue as unknown).toBe('newValueB'); + expect(modifiedPropB?.defaultValue as unknown).toBe('oldValueB'); + }); + + it('should detect a modified require call', () => { + const projectAnalysis: KarmaConfigAnalysis = { + settings: new Map([['plugin', { module: 'project-plugin' }]]), + hasUnsupportedValues: false, + }; + const defaultAnalysis: KarmaConfigAnalysis = { + settings: new Map([['plugin', { module: 'default-plugin' }]]), + hasUnsupportedValues: false, + }; + + const diff = compareKarmaConfigs(projectAnalysis, defaultAnalysis); + + expect(diff.isReliable).toBe(true); + expect(diff.modified.size).toBe(1); + const modified = diff.modified.get('plugin'); + expect((modified?.projectValue as RequireInfo).module).toBe('project-plugin'); + expect((modified?.defaultValue as RequireInfo).module).toBe('default-plugin'); + }); + + it('should detect a modified path.join call', () => { + const projectAnalysis: KarmaConfigAnalysis = { + settings: new Map([ + [ + 'coverageReporter', + { + dir: { + module: 'path', + export: 'join', + isCall: true, + arguments: ['__dirname', 'project-path'], + }, + }, + ], + ]), + hasUnsupportedValues: false, + }; + const defaultAnalysis: KarmaConfigAnalysis = { + settings: new Map([ + [ + 'coverageReporter', + { + dir: { + module: 'path', + export: 'join', + isCall: true, + arguments: ['__dirname', 'default-path'], + }, + }, + ], + ]), + hasUnsupportedValues: false, + }; + + const diff = compareKarmaConfigs(projectAnalysis, defaultAnalysis); + + expect(diff.isReliable).toBe(true); + expect(diff.modified.size).toBe(1); + const modified = diff.modified.get('coverageReporter') as { + projectValue: { dir: RequireInfo }; + defaultValue: { dir: RequireInfo }; + }; + expect(modified?.projectValue.dir.arguments as string[]).toEqual([ + '__dirname', + 'project-path', + ]); + expect(modified?.defaultValue.dir.arguments as string[]).toEqual([ + '__dirname', + 'default-path', + ]); + }); + + it('should detect an added require call', () => { + const projectAnalysis: KarmaConfigAnalysis = { + settings: new Map([ + ['propA', 'valueA'], + ['newPlugin', { module: 'new-plugin' }], + ]), + hasUnsupportedValues: false, + }; + const defaultAnalysis: KarmaConfigAnalysis = { + settings: new Map([['propA', 'valueA']]), + hasUnsupportedValues: false, + }; + + const diff = compareKarmaConfigs(projectAnalysis, defaultAnalysis); + + expect(diff.isReliable).toBe(true); + expect(diff.added.size).toBe(1); + expect((diff.added.get('newPlugin') as RequireInfo).module).toBe('new-plugin'); + }); + + it('should flag the diff as unreliable if the project config has unsupported values', () => { + const projectAnalysis: KarmaConfigAnalysis = { + settings: new Map(), + hasUnsupportedValues: true, + }; + const defaultAnalysis: KarmaConfigAnalysis = { + settings: new Map(), + hasUnsupportedValues: false, + }; + + const diff = compareKarmaConfigs(projectAnalysis, defaultAnalysis); + + expect(diff.isReliable).toBe(false); + }); + + it('should flag the diff as unreliable if the default config has unsupported values', () => { + const projectAnalysis: KarmaConfigAnalysis = { + settings: new Map(), + hasUnsupportedValues: false, + }; + const defaultAnalysis: KarmaConfigAnalysis = { + settings: new Map(), + hasUnsupportedValues: true, + }; + + const diff = compareKarmaConfigs(projectAnalysis, defaultAnalysis); + + expect(diff.isReliable).toBe(false); + }); + }); + + describe('compareKarmaConfigToDefault', () => { + let defaultConfig: string; + + beforeAll(async () => { + defaultConfig = await generateDefaultKarmaConfig('..', 'test-project', true); + }); + + it('should find no differences for the default config', async () => { + const diff = await compareKarmaConfigToDefault(defaultConfig, 'test-project', true); + + expect(diff.isReliable).toBe(true); + expect(diff.added.size).toBe(0); + expect(diff.removed.size).toBe(0); + expect(diff.modified.size).toBe(0); + }); + + it('should find differences for a modified config', async () => { + const modifiedConfig = defaultConfig + .replace(`restartOnFileChange: true`, `restartOnFileChange: false`) + .replace(`reporters: ['progress', 'kjhtml']`, `reporters: ['dots']`); + + const diff = await compareKarmaConfigToDefault(modifiedConfig, 'test-project', true); + + expect(diff.isReliable).toBe(true); + expect(diff.added.size).toBe(0); + expect(diff.removed.size).toBe(0); + expect(diff.modified.size).toBe(2); + const restartOnFileChange = diff.modified.get('restartOnFileChange'); + expect(restartOnFileChange?.projectValue as boolean).toBe(false); + expect(restartOnFileChange?.defaultValue as boolean).toBe(true); + const reporters = diff.modified.get('reporters'); + expect(reporters?.projectValue as string[]).toEqual(['dots']); + expect(reporters?.defaultValue as string[]).toEqual(['progress', 'kjhtml']); + }); + + it('should return an unreliable diff if the project config has unsupported values', async () => { + const modifiedConfig = defaultConfig.replace(`browsers: ['Chrome']`, `browsers: myBrowsers`); + const diff = await compareKarmaConfigToDefault(modifiedConfig, 'test-project', true); + + expect(diff.isReliable).toBe(false); + expect(diff.removed.has('browsers')).toBe(true); + }); + + it('should find no differences when devkit plugin is not needed', async () => { + const projectConfig = await generateDefaultKarmaConfig('..', 'test-project', false); + const diff = await compareKarmaConfigToDefault(projectConfig, 'test-project', false); + + expect(diff.isReliable).toBe(true); + expect(diff.added.size).toBe(0); + expect(diff.removed.size).toBe(0); + expect(diff.modified.size).toBe(0); + }); + }); +});