Repository navigation
Expand file tree
/
Copy pathbuild-options.ts
More file actions
339 lines (302 loc) · 12 KB
/
Copy pathbuild-options.ts
File metadata and controls
339 lines (302 loc) · 12 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
/**
* @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
*/
/**
* @fileoverview
* Provides Vitest-specific build options and virtual file contents for Angular unit testing.
*/
import type { BuilderContext } from '@angular-devkit/architect';
import path from 'node:path';
import { toPosixPath } from '../../../../utils/path';
import { createProjectResolver } from '../../../../utils/resolve-project';
import type { ApplicationBuilderInternalOptions } from '../../../application/options';
import { OutputHashing } from '../../../application/schema';
import { type NormalizedUnitTestBuilderOptions, injectTestingPolyfills } from '../../options';
import { findTests, getTestEntrypoints } from '../../test-discovery';
import { RunnerOptions } from '../api';
/**
* Creates the virtual file contents to initialize the Angular testing environment (TestBed).
*
* @param providersFile Optional path to a file that exports default providers.
* @param projectSourceRoot The root directory of the project source.
* @param teardown Whether to configure TestBed to destroy after each test.
* @returns The string content of the virtual initialization file.
*/
function createTestBedInitVirtualFile(
providersFile: string | undefined,
projectSourceRoot: string,
teardown: boolean,
hasLocalize: boolean,
): string {
let providersImport = 'const providers = [];';
if (providersFile) {
const relativePath = path.relative(projectSourceRoot, providersFile);
const { dir, name } = path.parse(relativePath);
const importPath = toPosixPath(path.join(dir, name));
providersImport = `import providers from './${importPath}';`;
}
// The DynamicDOMTestComponentRenderer is used to avoid stale document references
// when running Vitest in non-isolated mode with JSDOM. It looks up the
// document dynamically on every operation instead of caching it.
return `
${hasLocalize ? "import '@angular/localize/init';" : ''}
// Initialize the Angular testing environment
import { NgModule, provideZoneChangeDetection } from '@angular/core';
import { getTestBed, ɵgetCleanupHook as getCleanupHook, TestComponentRenderer } from '@angular/core/testing';
import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';
import { ɵgetDOM } from '@angular/common';
import { afterEach, beforeEach } from 'vitest';
${providersImport}
// The beforeEach and afterEach hooks are registered outside the globalThis guard.
// This ensures that the hooks are always applied, even in non-isolated browser environments.
// Same as https://github.com/angular/angular/blob/05a03d3f975771bb59c7eefd37c01fa127ee2229/packages/core/testing/srcs/test_hooks.ts#L21-L29
beforeEach(getCleanupHook(false));
afterEach(getCleanupHook(true));
class DynamicDOMTestComponentRenderer extends TestComponentRenderer {
insertRootElement(rootElId, tagName = 'div') {
this.removeAllRootElements();
const dom = ɵgetDOM();
const doc = dom.getDefaultDocument();
if (doc && doc.body) {
const rootElement = doc.createElement(tagName);
rootElement.setAttribute('id', rootElId);
doc.body.appendChild(rootElement);
}
}
removeAllRootElements() {
const dom = ɵgetDOM();
const doc = dom.getDefaultDocument();
if (doc && typeof doc.querySelectorAll === 'function') {
const oldRoots = doc.querySelectorAll('[id^=root]');
for (let i = 0; i < oldRoots.length; i++) {
dom.remove(oldRoots[i]);
}
}
}
}
const ANGULAR_TESTBED_SETUP = Symbol.for('@angular/cli/testbed-setup');
if (!globalThis[ANGULAR_TESTBED_SETUP]) {
globalThis[ANGULAR_TESTBED_SETUP] = true;
// The Angular TestBed needs to be initialized before any tests are run.
// In a non-isolated environment, this setup file can be executed multiple times.
// The guard condition above ensures that the setup is only performed once.
@NgModule({
providers: [
...(typeof Zone !== 'undefined' ? [provideZoneChangeDetection()] : []),
...providers,
{ provide: TestComponentRenderer, useClass: DynamicDOMTestComponentRenderer },
],
})
class TestModule {}
getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), {
errorOnUnknownElements: true,
errorOnUnknownProperties: true,
${teardown === false ? 'teardown: { destroyAfterEach: false },' : ''}
});
}
`;
}
/**
* Adjusts output hashing settings for testing purposes. For example, ensuring media
* is continued to be hashed to avoid overwriting assets, but turning off JavaScript hashing.
*
* @param hashing The original OutputHashing configuration.
* @returns The adjusted OutputHashing configuration.
*/
function adjustOutputHashing(hashing?: OutputHashing): OutputHashing {
switch (hashing) {
case OutputHashing.All:
case OutputHashing.Media:
// Ensure media is continued to be hashed to avoid overwriting of output media files
return OutputHashing.Media;
default:
return OutputHashing.None;
}
}
/**
* Injects Zone.js and Zone.js testing polyfills into the build options based on the
* project configuration and `polyfills` option.
*
* @param polyfills The configured polyfills from the test or build target.
* @param projectSourceRoot The root directory of the project source.
* @param logger The logger instance for reporting deprecation warnings.
* @returns An array of polyfill specifiers to use for testing.
*/
function injectZoneJsTestingPolyfills(
polyfills: string[] | undefined,
projectSourceRoot: string,
logger: BuilderContext['logger'],
): string[] {
if (polyfills) {
return injectTestingPolyfills(polyfills);
}
// If polyfills is undefined (e.g. library build target), attempt to load zone.js if installed.
try {
const projectResolve = createProjectResolver(projectSourceRoot);
projectResolve('zone.js');
logger.warn(
'Zone.js polyfills are being automatically injected because "zone.js" was detected in the project dependencies. ' +
'This behavior is deprecated. If your project is zoneless, set the "polyfills" option to an empty array ("[]") in the ' +
'test configuration. Otherwise, explicitly add "zone.js" to the "polyfills" option.',
);
return ['zone.js', 'zone.js/testing'];
} catch {
return [];
}
}
/**
* Generates options and virtual files for the Vitest test runner.
*
* Discovers specs matchers, creates entry points, decides polyfills strategy, and orchestrates
* internal ApplicationBuilder options.
*
* @param options The normalized unit test builder options.
* @param baseBuildOptions The base build config to derive testing config from.
* @param logger The logger instance for reporting deprecation warnings.
* @returns An async RunnerOptions configuration.
*/
export async function getVitestBuildOptions(
options: NormalizedUnitTestBuilderOptions,
baseBuildOptions: Partial<ApplicationBuilderInternalOptions>,
logger: BuilderContext['logger'],
): Promise<RunnerOptions> {
const {
workspaceRoot,
projectSourceRoot,
include,
polyfills,
exclude = [],
watch,
providersFile,
setupFiles,
} = options;
// Find test files
const testFiles = await findTests(include, exclude, workspaceRoot, projectSourceRoot);
if (testFiles.length === 0) {
throw new Error(
'No tests found matching the following patterns:\n' +
`- Included: ${include.join(', ')}\n` +
(exclude.length ? `- Excluded: ${exclude.join(', ')}\n` : '') +
`\nPlease check the 'test' target configuration in your project's 'angular.json' file.`,
);
}
const entryPoints = getTestEntrypoints(testFiles, {
projectSourceRoot,
workspaceRoot,
removeTestExtension: true,
});
const rootFiles = [...testFiles];
if (providersFile) {
rootFiles.push(providersFile);
}
if (setupFiles?.length) {
rootFiles.push(...setupFiles);
const setupEntryPoints = getTestEntrypoints(setupFiles, {
projectSourceRoot,
workspaceRoot,
removeTestExtension: false,
prefix: 'setup',
});
for (const [entryPoint, setupFile] of setupEntryPoints) {
entryPoints.set(entryPoint, setupFile);
}
}
// The Angular compiler facade must be loaded in a dedicated setup file before TestBed initialization.
// This ensures the compiler facade is published before 'init-testbed' or any shared code-split chunks
// (such as those from a configured 'providersFile') are evaluated.
entryPoints.set('init-compiler', 'angular:compiler-init');
entryPoints.set('init-testbed', 'angular:test-bed-init');
entryPoints.set('vitest-mock-patch', 'angular:vitest-mock-patch');
// The 'vitest' package is always external for testing purposes
const externalDependencies = ['vitest'];
if (baseBuildOptions.externalDependencies) {
externalDependencies.push(...baseBuildOptions.externalDependencies);
}
const buildOptions: Partial<ApplicationBuilderInternalOptions> = {
...baseBuildOptions,
polyfills: injectZoneJsTestingPolyfills(
polyfills ?? baseBuildOptions.polyfills,
projectSourceRoot,
logger,
),
watch,
incrementalResults: watch,
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: adjustOutputHashing(baseBuildOptions.outputHashing),
optimization: false,
namedChunks: false,
entryPoints,
rootFiles,
// Vitest's Node-based module loading emulation (vite-node) is not fully spec compliant and lacks
// live ESM bindings across chunk boundaries. This can cause uninitialized exports or break mocking.
// Disabling code splitting avoids shared chunks, but increases build and coverage memory/time.
disableCodeSplitting: !options.splitting,
// Enable support for vitest browser prebundling. Excludes can be controlled with a runnerConfig
// and the `optimizeDeps.exclude` option.
externalPackages: true,
externalDependencies,
};
let hasLocalize = false;
try {
const projectResolve = createProjectResolver(projectSourceRoot);
projectResolve('@angular/localize');
hasLocalize = true;
} catch {}
const testBedInitContents = createTestBedInitVirtualFile(
providersFile,
projectSourceRoot,
!options.debug,
hasLocalize,
);
const mockPatchContents = `
import { vi } from 'vitest';
const ANGULAR_VITEST_MOCK_PATCH = Symbol.for('@angular/cli/vitest-mock-patch');
if (!globalThis[ANGULAR_VITEST_MOCK_PATCH]) {
globalThis[ANGULAR_VITEST_MOCK_PATCH] = true;
const error = new Error(
'The "vi.mock" and related methods are not supported for relative imports with the Angular unit-test system. ' +
'Please use Angular TestBed for mocking dependencies.'
);
// Store original implementations
const { mock, doMock, importMock, unmock, doUnmock } = vi;
function patch(original) {
return (path, ...args) => {
// Check if the path is a string and starts with a character that indicates a relative path.
if (typeof path === 'string' && /^[./]/.test(path)) {
throw error;
}
// Call the original function for non-relative paths.
return original(path, ...args);
};
}
vi.mock = patch(mock);
vi.doMock = patch(doMock);
vi.importMock = patch(importMock);
vi.unmock = patch(unmock);
vi.doUnmock = patch(doUnmock);
}
`;
return {
buildOptions,
virtualFiles: {
'angular:compiler-init': "import '@angular/compiler';",
'angular:test-bed-init': testBedInitContents,
'angular:vitest-mock-patch': mockPatchContents,
},
testEntryPointMappings: entryPoints,
};
}