Skip to content

Commit 6c64560

Browse files
committed
refactor(@angular/build): introduce internal generic test runner API in unit-test builder
Refactors the unit-test builder to introduce a generic `TestRunner` API. This change decouples the main builder logic from the specifics of individual test runners like Karma and Vitest. The new API consists of two main parts: - `TestRunner`: A declarative definition of a test runner, including its name and hooks for creating an executor and getting build options. - `TestExecutor`: A stateful object that manages a test execution session. The Karma and Vitest runners have been refactored to implement this new API. The Karma runner is now marked as `isStandalone: true` to indicate that it manages its own build process. The Vitest runner now uses the `getBuildOptions` hook to provide its build configuration to the main builder. This refactoring makes the unit-test builder more extensible, allowing for new test runners to be added more easily in the future. It also improves the separation of concerns within the builder, making the code easier to understand and maintain.
1 parent 664959e commit 6c64560

File tree

9 files changed

+671
-473
lines changed

9 files changed

+671
-473
lines changed

packages/angular/build/src/builders/unit-test/builder.ts

Lines changed: 103 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,17 @@
77
*/
88

99
import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect';
10-
import type { ApplicationBuilderExtensions } from '../application/options';
10+
import assert from 'node:assert';
11+
import { createVirtualModulePlugin } from '../../tools/esbuild/virtual-module-plugin';
12+
import { assertIsError } from '../../utils/error';
13+
import { buildApplicationInternal } from '../application';
14+
import type {
15+
ApplicationBuilderExtensions,
16+
ApplicationBuilderInternalOptions,
17+
} from '../application/options';
18+
import { ResultKind } from '../application/results';
1119
import { normalizeOptions } from './options';
12-
import { useKarmaRunner } from './runners/karma';
13-
import { runVitest } from './runners/vitest';
20+
import type { TestRunner } from './runners/api';
1421
import type { Schema as UnitTestBuilderOptions } from './schema';
1522

1623
export type { UnitTestBuilderOptions };
@@ -36,17 +43,98 @@ export async function* execute(
3643
);
3744

3845
const normalizedOptions = await normalizeOptions(context, projectName, options);
39-
const { runnerName } = normalizedOptions;
40-
41-
switch (runnerName) {
42-
case 'karma':
43-
yield* await useKarmaRunner(context, normalizedOptions);
44-
break;
45-
case 'vitest':
46-
yield* runVitest(normalizedOptions, context, extensions);
47-
break;
48-
default:
49-
context.logger.error('Unknown test runner: ' + runnerName);
50-
break;
46+
const { runnerName, projectSourceRoot } = normalizedOptions;
47+
48+
// Dynamically load the requested runner
49+
let runner: TestRunner;
50+
try {
51+
const { default: runnerModule } = await import(`./runners/${runnerName}/index`);
52+
runner = runnerModule;
53+
} catch (e) {
54+
assertIsError(e);
55+
if (e.code !== 'ERR_MODULE_NOT_FOUND') {
56+
throw e;
57+
}
58+
context.logger.error(`Unknown test runner "${runnerName}".`);
59+
60+
return;
61+
}
62+
63+
// Create the stateful executor once
64+
await using executor = await runner.createExecutor(context, normalizedOptions);
65+
66+
if (runner.isStandalone) {
67+
yield* executor.execute({
68+
kind: ResultKind.Full,
69+
files: {},
70+
});
71+
72+
return;
73+
}
74+
75+
// Get base build options from the buildTarget
76+
const buildTargetOptions = (await context.validateOptions(
77+
await context.getTargetOptions(normalizedOptions.buildTarget),
78+
await context.getBuilderNameForTarget(normalizedOptions.buildTarget),
79+
)) as unknown as ApplicationBuilderInternalOptions;
80+
81+
// Get runner-specific build options from the hook
82+
const { buildOptions: runnerBuildOptions, virtualFiles } = await runner.getBuildOptions(
83+
normalizedOptions,
84+
buildTargetOptions,
85+
);
86+
87+
if (virtualFiles) {
88+
extensions ??= {};
89+
extensions.codePlugins ??= [];
90+
for (const [namespace, contents] of Object.entries(virtualFiles)) {
91+
extensions.codePlugins.push(
92+
createVirtualModulePlugin({
93+
namespace,
94+
loadContent: () => {
95+
return {
96+
contents,
97+
loader: 'js',
98+
resolveDir: projectSourceRoot,
99+
};
100+
},
101+
}),
102+
);
103+
}
104+
}
105+
106+
const { watch, tsConfig } = normalizedOptions;
107+
108+
// Prepare and run the application build
109+
const applicationBuildOptions = {
110+
// Base options
111+
...buildTargetOptions,
112+
watch,
113+
tsConfig,
114+
// Runner specific
115+
...runnerBuildOptions,
116+
} satisfies ApplicationBuilderInternalOptions;
117+
118+
for await (const buildResult of buildApplicationInternal(
119+
applicationBuildOptions,
120+
context,
121+
extensions,
122+
)) {
123+
if (buildResult.kind === ResultKind.Failure) {
124+
yield { success: false };
125+
continue;
126+
} else if (
127+
buildResult.kind !== ResultKind.Full &&
128+
buildResult.kind !== ResultKind.Incremental
129+
) {
130+
assert.fail(
131+
'A full and/or incremental build result is required from the application builder.',
132+
);
133+
}
134+
135+
assert(buildResult.files, 'Builder did not provide result files.');
136+
137+
// Pass the build artifacts to the executor
138+
yield* executor.execute(buildResult);
51139
}
52140
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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 { BuilderContext, BuilderOutput } from '@angular-devkit/architect';
10+
import type { ApplicationBuilderInternalOptions } from '../../application/options';
11+
import type { FullResult, IncrementalResult } from '../../application/results';
12+
import type { NormalizedUnitTestBuilderOptions } from '../options';
13+
14+
export interface RunnerOptions {
15+
buildOptions: Partial<ApplicationBuilderInternalOptions>;
16+
virtualFiles?: Record<string, string>;
17+
}
18+
19+
/**
20+
* Represents a stateful test execution session.
21+
* An instance of this is created for each `ng test` command.
22+
*/
23+
export interface TestExecutor {
24+
/**
25+
* Executes tests using the artifacts from a specific build.
26+
* This method can be called multiple times in watch mode.
27+
*
28+
* @param buildResult The output from the application builder.
29+
* @returns An async iterable builder output stream.
30+
*/
31+
execute(buildResult: FullResult | IncrementalResult): AsyncIterable<BuilderOutput>;
32+
33+
[Symbol.asyncDispose](): Promise<void>;
34+
}
35+
36+
/**
37+
* Represents the metadata and hooks for a specific test runner.
38+
*/
39+
export interface TestRunner {
40+
readonly name: string;
41+
readonly isStandalone?: boolean;
42+
43+
getBuildOptions(
44+
options: NormalizedUnitTestBuilderOptions,
45+
baseBuildOptions: Partial<ApplicationBuilderInternalOptions>,
46+
): RunnerOptions | Promise<RunnerOptions>;
47+
48+
/**
49+
* Creates a stateful executor for a test session.
50+
* This is called once at the start of the `ng test` command.
51+
*
52+
* @param context The Architect builder context.
53+
* @param options The normalized unit test options.
54+
* @returns A TestExecutor instance that will handle the test runs.
55+
*/
56+
createExecutor(
57+
context: BuilderContext,
58+
options: NormalizedUnitTestBuilderOptions,
59+
): Promise<TestExecutor>;
60+
}
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
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 { BuilderContext, BuilderOutput } from '@angular-devkit/architect';
10+
import type { ApplicationBuilderInternalOptions } from '../../../application/options';
11+
import type { KarmaBuilderOptions } from '../../../karma';
12+
import { NormalizedUnitTestBuilderOptions } from '../../options';
13+
import type { TestExecutor } from '../api';
14+
15+
export class KarmaExecutor implements TestExecutor {
16+
constructor(
17+
private context: BuilderContext,
18+
private options: NormalizedUnitTestBuilderOptions,
19+
) {}
20+
21+
async *execute(): AsyncIterable<BuilderOutput> {
22+
const { context, options: unitTestOptions } = this;
23+
24+
if (unitTestOptions.debug) {
25+
context.logger.warn(
26+
'The "karma" test runner does not support the "debug" option. The option will be ignored.',
27+
);
28+
}
29+
30+
if (unitTestOptions.setupFiles.length) {
31+
context.logger.warn(
32+
'The "karma" test runner does not support the "setupFiles" option. The option will be ignored.',
33+
);
34+
}
35+
36+
const buildTargetOptions = (await context.validateOptions(
37+
await context.getTargetOptions(unitTestOptions.buildTarget),
38+
await context.getBuilderNameForTarget(unitTestOptions.buildTarget),
39+
)) as unknown as ApplicationBuilderInternalOptions;
40+
41+
const karmaOptions: KarmaBuilderOptions = {
42+
tsConfig: unitTestOptions.tsConfig,
43+
polyfills: buildTargetOptions.polyfills,
44+
assets: buildTargetOptions.assets,
45+
scripts: buildTargetOptions.scripts,
46+
styles: buildTargetOptions.styles,
47+
inlineStyleLanguage: buildTargetOptions.inlineStyleLanguage,
48+
stylePreprocessorOptions: buildTargetOptions.stylePreprocessorOptions,
49+
externalDependencies: buildTargetOptions.externalDependencies,
50+
loader: buildTargetOptions.loader,
51+
define: buildTargetOptions.define,
52+
include: unitTestOptions.include,
53+
exclude: unitTestOptions.exclude,
54+
sourceMap: buildTargetOptions.sourceMap,
55+
progress: buildTargetOptions.progress,
56+
watch: unitTestOptions.watch,
57+
poll: buildTargetOptions.poll,
58+
preserveSymlinks: buildTargetOptions.preserveSymlinks,
59+
browsers: unitTestOptions.browsers?.join(','),
60+
codeCoverage: !!unitTestOptions.codeCoverage,
61+
codeCoverageExclude: unitTestOptions.codeCoverage?.exclude,
62+
fileReplacements: buildTargetOptions.fileReplacements,
63+
reporters: unitTestOptions.reporters,
64+
webWorkerTsConfig: buildTargetOptions.webWorkerTsConfig,
65+
aot: buildTargetOptions.aot,
66+
};
67+
68+
const { execute } = await import('../../../karma');
69+
70+
yield* execute(karmaOptions, context);
71+
}
72+
73+
async [Symbol.asyncDispose](): Promise<void> {
74+
// The Karma builder handles its own teardown
75+
}
76+
}

packages/angular/build/src/builders/unit-test/runners/karma/index.ts

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,4 +6,25 @@
66
* found in the LICENSE file at https://angular.dev/license
77
*/
88

9-
export { useKarmaRunner } from './runner';
9+
import type { TestRunner } from '../api';
10+
import { KarmaExecutor } from './executor';
11+
12+
/**
13+
* A declarative definition of the Karma test runner.
14+
*/
15+
const KarmaTestRunner: TestRunner = {
16+
name: 'karma',
17+
isStandalone: true,
18+
19+
getBuildOptions() {
20+
return {
21+
buildOptions: {},
22+
};
23+
},
24+
25+
async createExecutor(context, options) {
26+
return new KarmaExecutor(context, options);
27+
},
28+
};
29+
30+
export default KarmaTestRunner;

packages/angular/build/src/builders/unit-test/runners/karma/runner.ts

Lines changed: 0 additions & 67 deletions
This file was deleted.

0 commit comments

Comments
 (0)