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
247 lines (221 loc) · 7.87 KB
/
executor.ts
File metadata and controls
247 lines (221 loc) · 7.87 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
/**
* @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 { 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 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,
) {
this.projectName = projectName;
this.options = options;
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);
// 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) {
// 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();
yield { success: testModules.every((testModule) => testModule.ok()) };
}
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,
} = 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,
this.options.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: this.options.projectSourceRoot,
projectName,
buildResultFiles: this.buildResultFiles,
testFileToEntryPoint: this.testFileToEntryPoint,
});
const debugOptions = debug
? {
inspectBrk: true,
isolate: false,
fileParallelism: false,
}
: {};
const runnerConfig = this.options.runnerConfig;
const externalConfigPath =
runnerConfig === true
? await findVitestBaseConfig([this.options.projectRoot, this.options.workspaceRoot])
: runnerConfig;
return startVitest(
'test',
undefined,
{
config: externalConfigPath,
root: workspaceRoot,
project: projectName,
outputFile,
testNamePattern: this.options.filter,
watch,
ui,
...debugOptions,
},
{
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: this.options.projectSourceRoot,
optimizeDepsInclude: this.externalMetadata.implicitBrowser,
reporters,
setupFiles: testSetupFiles,
projectPlugins,
include: [...this.testFileToEntryPoint.keys()].filter(
// Filter internal entries
(entry) => !entry.startsWith('angular:'),
),
}),
],
},
);
}
}