forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexecutor.ts
More file actions
290 lines (259 loc) · 9.57 KB
/
executor.ts
File metadata and controls
290 lines (259 loc) · 9.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
/**
* @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 { BuilderContext, BuilderOutput } from '@angular-devkit/architect';
import assert from 'node:assert';
import path from 'node:path';
import type { Vitest } from 'vitest/node';
import {
DevServerExternalResultMetadata,
updateExternalMetadata,
} from '../../../../tools/vite/utils';
import { assertIsError } from '../../../../utils/error';
import {
type FullResult,
type IncrementalResult,
type ResultFile,
ResultKind,
} from '../../../application/results';
import { NormalizedUnitTestBuilderOptions } from '../../options';
import type { TestExecutor } from '../api';
import { setupBrowserConfiguration } from './browser-provider';
import { findVitestBaseConfig } from './configuration';
import { createVitestConfigPlugin, createVitestPlugins } from './plugins';
export class VitestExecutor implements TestExecutor {
private vitest: Vitest | undefined;
private normalizePath: ((id: string) => string) | undefined;
private readonly projectName: string;
private readonly options: NormalizedUnitTestBuilderOptions;
private readonly logger: BuilderContext['logger'];
private readonly buildResultFiles = new Map<string, ResultFile>();
private readonly externalMetadata: DevServerExternalResultMetadata = {
implicitBrowser: [],
implicitServer: [],
explicitBrowser: [],
explicitServer: [],
};
// This is a reverse map of the entry points created in `build-options.ts`.
// It is used by the in-memory provider plugin to map the requested test file
// path back to its bundled output path.
// Example: `Map<'/path/to/src/app.spec.ts', 'spec-src-app-spec'>`
private readonly testFileToEntryPoint = new Map<string, string>();
private readonly entryPointToTestFile = new Map<string, string>();
constructor(
projectName: string,
options: NormalizedUnitTestBuilderOptions,
testEntryPointMappings: Map<string, string> | undefined,
logger: BuilderContext['logger'],
) {
this.projectName = projectName;
this.options = options;
this.logger = logger;
if (testEntryPointMappings) {
for (const [entryPoint, testFile] of testEntryPointMappings) {
this.testFileToEntryPoint.set(testFile, entryPoint);
this.entryPointToTestFile.set(entryPoint + '.js', testFile);
}
}
}
async *execute(buildResult: FullResult | IncrementalResult): AsyncIterable<BuilderOutput> {
this.normalizePath ??= (await import('vite')).normalizePath;
if (buildResult.kind === ResultKind.Full) {
this.buildResultFiles.clear();
for (const [path, file] of Object.entries(buildResult.files)) {
this.buildResultFiles.set(this.normalizePath(path), file);
}
} else {
for (const file of buildResult.removed) {
this.buildResultFiles.delete(this.normalizePath(file.path));
}
for (const [path, file] of Object.entries(buildResult.files)) {
this.buildResultFiles.set(this.normalizePath(path), file);
}
}
updateExternalMetadata(buildResult, this.externalMetadata, undefined, true);
// Reset the exit code to allow for a clean state.
// This is necessary because Vitest may set the exit code on failure, which can
// affect subsequent runs in watch mode or when running multiple builders.
process.exitCode = 0;
// Initialize Vitest if not already present.
this.vitest ??= await this.initializeVitest();
const vitest = this.vitest;
let testResults;
if (buildResult.kind === ResultKind.Incremental) {
// To rerun tests, Vitest needs the original test file paths, not the output paths.
const modifiedSourceFiles = new Set<string>();
for (const modifiedFile of [...buildResult.modified, ...buildResult.added]) {
// The `modified` files in the build result are the output paths.
// We need to find the original source file path to pass to Vitest.
const source = this.entryPointToTestFile.get(modifiedFile);
if (source) {
modifiedSourceFiles.add(source);
}
vitest.invalidateFile(
this.normalizePath(path.join(this.options.workspaceRoot, modifiedFile)),
);
}
const specsToRerun = [];
for (const file of modifiedSourceFiles) {
vitest.invalidateFile(file);
const specs = vitest.getModuleSpecifications(file);
if (specs) {
specsToRerun.push(...specs);
}
}
if (specsToRerun.length > 0) {
testResults = await vitest.rerunTestSpecifications(specsToRerun);
}
}
// Check if all the tests pass to calculate the result
const testModules = testResults?.testModules ?? this.vitest.state.getTestModules();
let success = testModules.every((testModule) => testModule.ok());
// Vitest does not return a failure result when coverage thresholds are not met.
// Instead, it sets the process exit code to 1.
// We check this exit code to determine if the test run should be considered a failure.
if (success && process.exitCode === 1) {
success = false;
// Reset the exit code to prevent it from carrying over to subsequent runs/builds
process.exitCode = 0;
}
yield { success };
}
async [Symbol.asyncDispose](): Promise<void> {
await this.vitest?.close();
}
private prepareSetupFiles(): string[] {
const { setupFiles } = this.options;
// Add setup file entries for TestBed initialization and project polyfills
const testSetupFiles = ['init-testbed.js', ...setupFiles];
// TODO: Provide additional result metadata to avoid needing to extract based on filename
if (this.buildResultFiles.has('polyfills.js')) {
testSetupFiles.unshift('polyfills.js');
}
return testSetupFiles;
}
private async initializeVitest(): Promise<Vitest> {
const {
coverage,
reporters,
outputFile,
workspaceRoot,
browsers,
debug,
watch,
browserViewport,
ui,
projectRoot,
runnerConfig,
projectSourceRoot,
cacheOptions,
} = this.options;
const projectName = this.projectName;
let vitestNodeModule;
try {
vitestNodeModule = await import('vitest/node');
} catch (error: unknown) {
assertIsError(error);
if (error.code !== 'ERR_MODULE_NOT_FOUND') {
throw error;
}
throw new Error(
'The `vitest` package was not found. Please install the package and rerun the test command.',
);
}
const { startVitest } = vitestNodeModule;
// Setup vitest browser options if configured
const browserOptions = await setupBrowserConfiguration(
browsers,
debug,
projectSourceRoot,
browserViewport,
);
if (browserOptions.errors?.length) {
throw new Error(browserOptions.errors.join('\n'));
}
assert(
this.buildResultFiles.size > 0,
'buildResult must be available before initializing vitest',
);
const testSetupFiles = this.prepareSetupFiles();
const projectPlugins = createVitestPlugins({
workspaceRoot,
projectSourceRoot,
projectName,
buildResultFiles: this.buildResultFiles,
testFileToEntryPoint: this.testFileToEntryPoint,
});
const debugOptions = debug
? {
inspectBrk: true,
isolate: false,
fileParallelism: false,
}
: {};
const externalConfigPath =
runnerConfig === true
? await findVitestBaseConfig([projectRoot, workspaceRoot])
: runnerConfig;
let project = projectName;
if (debug && browserOptions.browser?.instances) {
if (browserOptions.browser.instances.length > 1) {
this.logger.warn(
'Multiple browsers are configured, but only the first browser will be used for debugging.',
);
}
// When running browser tests, Vitest appends the browser name to the project identifier.
// The project name must match this augmented name to ensure the correct project is targeted.
project = `${projectName} (${browserOptions.browser.instances[0].browser})`;
}
// Filter internal entries and setup files from the include list
const internalEntries = ['angular:'];
const setupFileSet = new Set(testSetupFiles);
const include = [...this.testFileToEntryPoint.keys()].filter((entry) => {
return (
!internalEntries.some((internal) => entry.startsWith(internal)) && !setupFileSet.has(entry)
);
});
return startVitest(
'test',
undefined,
{
config: externalConfigPath,
root: workspaceRoot,
project,
outputFile,
cache: cacheOptions.enabled ? undefined : false,
testNamePattern: this.options.filter,
watch,
...(typeof ui === 'boolean' ? { ui } : {}),
...debugOptions,
},
{
// Note `.vitest` is auto appended to the path.
cacheDir: cacheOptions.path,
server: {
// Disable the actual file watcher. The boolean watch option above should still
// be enabled as it controls other internal behavior related to rerunning tests.
watch: null,
},
plugins: [
await createVitestConfigPlugin({
browser: browserOptions.browser,
coverage,
projectName,
projectSourceRoot,
optimizeDepsInclude: this.externalMetadata.implicitBrowser,
reporters,
setupFiles: testSetupFiles,
projectPlugins,
include,
}),
],
},
);
}
}