Skip to content

Commit c0dbeb7

Browse files
committed
feat(@angular/build): add runnerArgs option to unit-test builder
The unit-test builder now supports a `runnerArgs` option that provides additional command line arguments to the Vitest runner. For example, `ng test --runner-args=--update` updates existing snapshots and `ng test --runner-args=--bail=1` stops the run after the first failure. The option can also be configured within the `angular.json` file. The arguments are parsed with the Vitest command line parser and then validated against a list of supported Vitest options. The Vitest parser accepts unknown options, command names, and test file filters without error. The validation ensures that a misspelled or unsupported argument fails the build with a descriptive message instead of being ignored. Vitest options with an equivalent builder option, such as `--reporter` and `--coverage`, are rejected with a reference to the builder option. The initially supported Vitest options are `--allowOnly`, `--bail`, `--disableConsoleIntercept`, `--expandSnapshotDiff`, `--maxWorkers`, `--printConsoleTrace`, `--retry`, `--sequence.seed`, `--sequence.shuffle`, `--shard`, `--testTimeout`, and `--update`. The supported options take precedence over a Vitest configuration file but not over the other builder options. The option is not available for the Karma runner.
1 parent a9b12f1 commit c0dbeb7

12 files changed

Lines changed: 739 additions & 3 deletions

File tree

‎goldens/public-api/angular/build/index.api.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,7 @@ export type UnitTestBuilderOptions = {
242242
quiet?: boolean;
243243
reporters?: SchemaReporter[];
244244
runner?: Runner;
245+
runnerArgs?: string[];
245246
runnerConfig?: RunnerConfig;
246247
setupFiles?: string[];
247248
splitting?: boolean;

‎packages/angular/build/BUILD.bazel‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,7 @@ ts_project(
155155
":node_modules/@babel/core",
156156
":node_modules/@parcel/watcher",
157157
":node_modules/oxc-parser",
158+
":node_modules/vitest",
158159
"//:node_modules/@angular/compiler-cli",
159160
"//:node_modules/@angular/router",
160161
"//:node_modules/@types/jasmine",

‎packages/angular/build/src/builders/unit-test/options.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,7 @@ export async function normalizeOptions(
7979
browserViewport,
8080
ui,
8181
runnerConfig,
82+
runnerArgs,
8283
isolate,
8384
splitting = true,
8485
polyfills,
@@ -92,6 +93,10 @@ export async function normalizeOptions(
9293
throw new Error('The "isolate" option is only available for the "vitest" runner.');
9394
}
9495

96+
if (runnerArgs?.length && (runner ?? Runner.Vitest) !== Runner.Vitest) {
97+
throw new Error('The "runnerArgs" option is only available for the "vitest" runner.');
98+
}
99+
95100
const [width, height] = browserViewport?.split('x').map(Number) ?? [];
96101

97102
let tsConfig = options.tsConfig;
@@ -170,6 +175,7 @@ export async function normalizeOptions(
170175
? true
171176
: path.resolve(workspaceRoot, runnerConfig)
172177
: runnerConfig,
178+
runnerArgs: runnerArgs?.length ? runnerArgs : undefined,
173179
};
174180
}
175181

‎packages/angular/build/src/builders/unit-test/runners/vitest/cli-options.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,16 +26,20 @@ export interface VitestCliOptionsSource extends Pick<
2626
* @param options The normalized builder options to convert.
2727
* @param project The name of the Vitest project to execute.
2828
* @param configPath The path to an external Vitest configuration file, if any.
29+
* @param runnerArgOptions The Vitest CLI options from the `runnerArgs` builder option, if any.
30+
* The options created from the other builder options take precedence over these.
2931
* @returns The Vitest CLI options.
3032
*/
3133
export function createVitestCliOptions(
3234
options: VitestCliOptionsSource,
3335
project: string,
3436
configPath: string | false | undefined,
37+
runnerArgOptions?: CliOptions,
3538
): CliOptions {
3639
const { workspaceRoot, watch, outputFile, cacheOptions, filter, ui, debug } = options;
3740

3841
return {
42+
...runnerArgOptions,
3943
config: configPath,
4044
root: workspaceRoot,
4145
project,

‎packages/angular/build/src/builders/unit-test/runners/vitest/cli-options_spec.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,25 @@ describe('createVitestCliOptions', () => {
7272
expect(options.fileParallelism).toBeFalse();
7373
});
7474

75+
it('should include the options from the runner arguments', () => {
76+
const options = createVitestCliOptions(baseOptions, 'app', false, { update: true, bail: 1 });
77+
78+
expect(options.update).toBeTrue();
79+
expect(options.bail).toBe(1);
80+
});
81+
82+
it('should prefer the builder options over the options from the runner arguments', () => {
83+
const options = createVitestCliOptions({ ...baseOptions, filter: 'builder' }, 'app', false, {
84+
root: '/other',
85+
watch: true,
86+
testNamePattern: 'runner',
87+
});
88+
89+
expect(options.root).toBe('/workspace');
90+
expect(options.watch).toBeFalse();
91+
expect(options.testNamePattern).toBe('builder');
92+
});
93+
7594
it('should not configure the inspector when not debugging', () => {
7695
const options = createVitestCliOptions(baseOptions, 'app', false);
7796

‎packages/angular/build/src/builders/unit-test/runners/vitest/executor.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import { setupBrowserConfiguration } from './browser-provider';
3232
import { createVitestCliOptions } from './cli-options';
3333
import { findVitestBaseConfig } from './configuration';
3434
import { createVitestConfigPlugin, createVitestPlugins } from './plugins';
35+
import type { RunnerArgOptions } from './runner-args';
3536

3637
enum DebugLogLevel {
3738
Info = 1,
@@ -44,6 +45,7 @@ export class VitestExecutor implements TestExecutor {
4445
private readonly projectName: string;
4546
private readonly options: NormalizedUnitTestBuilderOptions;
4647
private readonly logger: BuilderContext['logger'];
48+
private readonly runnerArgOptions: RunnerArgOptions | undefined;
4749
private readonly buildResultFiles = new Map<string, ResultFile>();
4850
private readonly externalMetadata: DevServerExternalResultMetadata = {
4951
implicitBrowser: [],
@@ -65,13 +67,15 @@ export class VitestExecutor implements TestExecutor {
6567
options: NormalizedUnitTestBuilderOptions,
6668
testEntryPointMappings: Map<string, string> | undefined,
6769
logger: BuilderContext['logger'],
70+
runnerArgOptions?: RunnerArgOptions,
6871
) {
6972
const level = parseInt(process.env['NG_TEST_LOG'] ?? '0', 10);
7073
this.debugLevel = isNaN(level) ? 0 : level;
7174

7275
this.projectName = projectName;
7376
this.options = options;
7477
this.logger = logger;
78+
this.runnerArgOptions = runnerArgOptions;
7579

7680
this.debugLog(DebugLogLevel.Info, 'VitestExecutor instantiated.');
7781
this.debugLog(DebugLogLevel.Verbose, 'NormalizedUnitTestBuilderOptions:', options);
@@ -380,7 +384,12 @@ export class VitestExecutor implements TestExecutor {
380384
}
381385
this.debugLog(DebugLogLevel.Verbose, 'Included test files (after filtering):', include);
382386

383-
const vitestConfig = createVitestCliOptions(this.options, project, externalConfigPath);
387+
const vitestConfig = createVitestCliOptions(
388+
this.options,
389+
project,
390+
externalConfigPath,
391+
this.runnerArgOptions?.cli,
392+
);
384393
const vitestServerConfig = {
385394
// Note `.vitest` is auto appended to the path.
386395
cacheDir: cacheOptions.path,
@@ -399,6 +408,7 @@ export class VitestExecutor implements TestExecutor {
399408
watch,
400409
isolate: this.options.isolate,
401410
preserveSymlinks: this.options.preserveSymlinks,
411+
runnerArgOptions: this.runnerArgOptions?.project,
402412
}),
403413
],
404414
};

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

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import type { TestRunner } from '../api';
1111
import { DependencyChecker } from '../dependency-checker';
1212
import { getVitestBuildOptions } from './build-options';
1313
import { VitestExecutor } from './executor';
14+
import { type RunnerArgOptions, parseRunnerArgs } from './runner-args';
1415

1516
/**
1617
* A declarative definition of the Vitest test runner.
@@ -79,7 +80,20 @@ const VitestTestRunner: TestRunner = {
7980
context.logger.info('Automatically searching for and using Vitest configuration file.');
8081
}
8182

82-
return new VitestExecutor(projectName, options, testEntryPointMappings, context.logger);
83+
// Parse and validate any additional Vitest arguments prior to the build to fail fast.
84+
let runnerArgOptions: RunnerArgOptions | undefined;
85+
if (options.runnerArgs) {
86+
const { parseCLI } = await import('vitest/node');
87+
runnerArgOptions = parseRunnerArgs(options.runnerArgs, parseCLI);
88+
}
89+
90+
return new VitestExecutor(
91+
projectName,
92+
options,
93+
testEntryPointMappings,
94+
context.logger,
95+
runnerArgOptions,
96+
);
8397
},
8498
};
8599

‎packages/angular/build/src/builders/unit-test/runners/vitest/plugins.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,9 @@ interface VitestConfigPluginOptions {
5757
watch: boolean;
5858
isolate: boolean | undefined;
5959
preserveSymlinks?: boolean;
60+
61+
/** Vitest project options from the `runnerArgs` builder option. */
62+
runnerArgOptions?: Record<string, unknown>;
6063
}
6164

6265
async function findTestEnvironment(
@@ -307,8 +310,13 @@ export async function createVitestConfigPlugin(
307310
resolve,
308311
};
309312

313+
// The order of precedence from lowest to highest is the builder defaults, the Vitest
314+
// configuration file, the `runnerArgs` builder option, and then the other builder options.
310315
const projectBase = mergeConfig(projectDefaults, testConfig ? { test: testConfig } : {});
311-
const projectConfig = mergeConfig(projectBase, projectOverrides);
316+
const projectWithRunnerArgs = options.runnerArgOptions
317+
? mergeConfig(projectBase, { test: options.runnerArgOptions })
318+
: projectBase;
319+
const projectConfig = mergeConfig(projectWithRunnerArgs, projectOverrides);
312320

313321
return {
314322
test: {

0 commit comments

Comments
 (0)