forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuilder.ts
More file actions
379 lines (336 loc) · 12.4 KB
/
builder.ts
File metadata and controls
379 lines (336 loc) · 12.4 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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/**
* @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 { randomUUID } from 'node:crypto';
import { createRequire } from 'node:module';
import path from 'node:path';
import { createVirtualModulePlugin } from '../../tools/esbuild/virtual-module-plugin';
import { assertIsError } from '../../utils/error';
import { loadEsmModule } from '../../utils/load-esm';
import { buildApplicationInternal } from '../application';
import type {
ApplicationBuilderExtensions,
ApplicationBuilderInternalOptions,
} from '../application/options';
import { ResultKind } from '../application/results';
import { OutputHashing } from '../application/schema';
import { writeTestFiles } from '../karma/application_builder';
import { findTests, getTestEntrypoints } from '../karma/find-tests';
import { useKarmaBuilder } from './karma-bridge';
import { normalizeOptions } from './options';
import type { Schema as UnitTestOptions } from './schema';
export type { UnitTestOptions };
/**
* @experimental Direct usage of this function is considered experimental.
*/
// eslint-disable-next-line max-lines-per-function
export async function* execute(
options: UnitTestOptions,
context: BuilderContext,
extensions: ApplicationBuilderExtensions = {},
): AsyncIterable<BuilderOutput> {
// Determine project name from builder context target
const projectName = context.target?.project;
if (!projectName) {
context.logger.error(
`The "${context.builder.builderName}" builder requires a target to be specified.`,
);
return;
}
context.logger.warn(
`NOTE: The "${context.builder.builderName}" builder is currently EXPERIMENTAL and not ready for production use.`,
);
const normalizedOptions = await normalizeOptions(context, projectName, options);
const { projectSourceRoot, workspaceRoot, runnerName } = normalizedOptions;
// Translate options and use karma builder directly if specified
if (runnerName === 'karma') {
const karmaBridge = await useKarmaBuilder(context, normalizedOptions);
yield* karmaBridge;
return;
}
if (runnerName !== 'vitest') {
context.logger.error('Unknown test runner: ' + runnerName);
return;
}
// Find test files
const testFiles = await findTests(
normalizedOptions.include,
normalizedOptions.exclude,
workspaceRoot,
projectSourceRoot,
);
if (testFiles.length === 0) {
context.logger.error('No tests found.');
return { success: false };
}
const entryPoints = getTestEntrypoints(testFiles, { projectSourceRoot, workspaceRoot });
entryPoints.set('init-testbed', 'angular:test-bed-init');
let vitestNodeModule;
try {
vitestNodeModule = await loadEsmModule<typeof import('vitest/node')>('vitest/node');
} catch (error: unknown) {
assertIsError(error);
if (error.code !== 'ERR_MODULE_NOT_FOUND') {
throw error;
}
context.logger.error(
'The `vitest` package was not found. Please install the package and rerun the test command.',
);
return;
}
const { startVitest } = vitestNodeModule;
// Setup test file build options based on application build target options
const buildTargetOptions = (await context.validateOptions(
await context.getTargetOptions(normalizedOptions.buildTarget),
await context.getBuilderNameForTarget(normalizedOptions.buildTarget),
)) as unknown as ApplicationBuilderInternalOptions;
if (buildTargetOptions.polyfills?.includes('zone.js')) {
buildTargetOptions.polyfills.push('zone.js/testing');
}
const outputPath = path.join(context.workspaceRoot, generateOutputPath());
const buildOptions: ApplicationBuilderInternalOptions = {
...buildTargetOptions,
watch: normalizedOptions.watch,
incrementalResults: normalizedOptions.watch,
outputPath,
index: false,
browser: undefined,
server: undefined,
outputMode: undefined,
localize: false,
budgets: [],
serviceWorker: false,
appShell: false,
ssr: false,
prerender: false,
sourceMap: { scripts: true, vendor: false, styles: false },
outputHashing: OutputHashing.None,
optimization: false,
tsConfig: normalizedOptions.tsConfig,
entryPoints,
externalDependencies: ['vitest', ...(buildTargetOptions.externalDependencies ?? [])],
};
extensions ??= {};
extensions.codePlugins ??= [];
const virtualTestBedInit = createVirtualModulePlugin({
namespace: 'angular:test-bed-init',
loadContent: async () => {
const contents: string[] = [
// Initialize the Angular testing environment
`import { NgModule } from '@angular/core';`,
`import { getTestBed, ɵgetCleanupHook as getCleanupHook } from '@angular/core/testing';`,
`import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';`,
'',
normalizedOptions.providersFile
? `import providers from './${path
.relative(projectSourceRoot, normalizedOptions.providersFile)
.replace(/.[mc]?ts$/, '')
.replace(/\\/g, '/')}'`
: 'const providers = [];',
'',
// Same as https://github.com/angular/angular/blob/05a03d3f975771bb59c7eefd37c01fa127ee2229/packages/core/testing/src/test_hooks.ts#L21-L29
`beforeEach(getCleanupHook(false));`,
`afterEach(getCleanupHook(true));`,
'',
`@NgModule({`,
` providers,`,
`})`,
`export class TestModule {}`,
'',
`getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), {`,
` errorOnUnknownElements: true,`,
` errorOnUnknownProperties: true,`,
'});',
];
return {
contents: contents.join('\n'),
loader: 'js',
resolveDir: projectSourceRoot,
};
},
});
extensions.codePlugins.unshift(virtualTestBedInit);
let instance: import('vitest/node').Vitest | undefined;
// Setup vitest browser options if configured
const { browser, errors } = setupBrowserConfiguration(
normalizedOptions.browsers,
normalizedOptions.debug,
projectSourceRoot,
);
if (errors?.length) {
errors.forEach((error) => context.logger.error(error));
return { success: false };
}
// Add setup file entries for TestBed initialization and project polyfills
const setupFiles = ['init-testbed.js'];
if (buildTargetOptions?.polyfills?.length) {
setupFiles.push('polyfills.js');
}
const debugOptions = normalizedOptions.debug
? {
inspectBrk: true,
isolate: false,
fileParallelism: false,
}
: {};
try {
for await (const result of buildApplicationInternal(buildOptions, context, extensions)) {
if (result.kind === ResultKind.Failure) {
continue;
} else if (result.kind !== ResultKind.Full && result.kind !== ResultKind.Incremental) {
assert.fail(
'A full and/or incremental build result is required from the application builder.',
);
}
assert(result.files, 'Builder did not provide result files.');
await writeTestFiles(result.files, outputPath);
instance ??= await startVitest(
'test',
undefined /* cliFilters */,
{
// Disable configuration file resolution/loading
config: false,
root: workspaceRoot,
project: ['base', projectName],
name: 'base',
include: [],
reporters: normalizedOptions.reporters ?? ['default'],
watch: normalizedOptions.watch,
coverage: {
enabled: !!normalizedOptions.codeCoverage,
excludeAfterRemap: true,
exclude: normalizedOptions.codeCoverage?.exclude,
// Special handling for `reporter` due to an undefined value causing upstream failures
...(normalizedOptions.codeCoverage?.reporters
? { reporter: normalizedOptions.codeCoverage.reporters }
: {}),
},
...debugOptions,
},
{
plugins: [
{
name: 'angular:project-init',
async configureVitest(context) {
// Create a subproject that can be configured with plugins for browser mode.
// Plugins defined directly in the vite overrides will not be present in the
// browser specific Vite instance.
await context.injectTestProjects({
test: {
name: projectName,
root: outputPath,
globals: true,
setupFiles,
// Use `jsdom` if no browsers are explicitly configured.
// `node` is effectively no "environment" and the default.
environment: browser ? 'node' : 'jsdom',
browser,
},
plugins: [
{
name: 'angular:html-index',
transformIndexHtml() {
// Add all global stylesheets
return (
Object.entries(result.files)
// TODO: Expand this to all configured global stylesheets
.filter(([file]) => file === 'styles.css')
.map(([styleUrl]) => ({
tag: 'link',
attrs: {
'href': styleUrl,
'rel': 'stylesheet',
},
injectTo: 'head',
}))
);
},
},
],
});
},
},
],
},
);
// Check if all the tests pass to calculate the result
const testModules = instance.state.getTestModules();
yield { success: testModules.every((testModule) => testModule.ok()) };
}
} finally {
if (normalizedOptions.watch) {
// Vitest will automatically close if not using watch mode
await instance?.close();
}
}
}
function findBrowserProvider(
projectResolver: NodeJS.RequireResolve,
): import('vitest/node').BrowserBuiltinProvider | undefined {
// One of these must be installed in the project to use browser testing
const vitestBuiltinProviders = ['playwright', 'webdriverio'] as const;
for (const providerName of vitestBuiltinProviders) {
try {
projectResolver(providerName);
return providerName;
} catch {}
}
}
function setupBrowserConfiguration(
browsers: string[] | undefined,
debug: boolean,
projectSourceRoot: string,
): { browser?: import('vitest/node').BrowserConfigOptions; errors?: string[] } {
if (browsers === undefined) {
return {};
}
const projectResolver = createRequire(projectSourceRoot + '/').resolve;
let errors: string[] | undefined;
try {
projectResolver('@vitest/browser');
} catch {
errors ??= [];
errors.push(
'The "browsers" option requires the "@vitest/browser" package to be installed within the project.' +
' Please install this package and rerun the test command.',
);
}
const provider = findBrowserProvider(projectResolver);
if (!provider) {
errors ??= [];
errors.push(
'The "browsers" option requires either "playwright" or "webdriverio" to be installed within the project.' +
' Please install one of these packages and rerun the test command.',
);
}
// Vitest current requires the playwright browser provider to use the inspect-brk option used by "debug"
if (debug && provider !== 'playwright') {
errors ??= [];
errors.push(
'Debugging browser mode tests currently requires the use of "playwright".' +
' Please install this package and rerun the test command.',
);
}
if (errors) {
return { errors };
}
const browser = {
enabled: true,
provider,
instances: browsers.map((browserName) => ({
browser: browserName,
})),
};
return { browser };
}
function generateOutputPath(): string {
const datePrefix = new Date().toISOString().replaceAll(/[-:.]/g, '');
const uuidSuffix = randomUUID().slice(0, 8);
return path.join('dist', 'test-out', `${datePrefix}-${uuidSuffix}`);
}