|
| 1 | +/** |
| 2 | + * @license |
| 3 | + * Copyright Google LLC All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.dev/license |
| 7 | + */ |
| 8 | + |
| 9 | +import type { BuilderContext, BuilderOutput } from '@angular-devkit/architect'; |
| 10 | +import assert from 'node:assert'; |
| 11 | +import { randomUUID } from 'node:crypto'; |
| 12 | +import path from 'node:path'; |
| 13 | +import { createVirtualModulePlugin } from '../../tools/esbuild/virtual-module-plugin'; |
| 14 | +import { loadEsmModule } from '../../utils/load-esm'; |
| 15 | +import { buildApplicationInternal } from '../application'; |
| 16 | +import type { |
| 17 | + ApplicationBuilderExtensions, |
| 18 | + ApplicationBuilderInternalOptions, |
| 19 | +} from '../application/options'; |
| 20 | +import { ResultKind } from '../application/results'; |
| 21 | +import { OutputHashing } from '../application/schema'; |
| 22 | +import { writeTestFiles } from '../karma/application_builder'; |
| 23 | +import { findTests, getTestEntrypoints } from '../karma/find-tests'; |
| 24 | +import { normalizeOptions } from './options'; |
| 25 | +import type { Schema as UnitTestOptions } from './schema'; |
| 26 | + |
| 27 | +export type { UnitTestOptions }; |
| 28 | + |
| 29 | +/** |
| 30 | + * @experimental Direct usage of this function is considered experimental. |
| 31 | + */ |
| 32 | +export async function* execute( |
| 33 | + options: UnitTestOptions, |
| 34 | + context: BuilderContext, |
| 35 | + extensions: ApplicationBuilderExtensions = {}, |
| 36 | +): AsyncIterable<BuilderOutput> { |
| 37 | + // Determine project name from builder context target |
| 38 | + const projectName = context.target?.project; |
| 39 | + if (!projectName) { |
| 40 | + context.logger.error( |
| 41 | + `The "${context.builder.builderName}" builder requires a target to be specified.`, |
| 42 | + ); |
| 43 | + |
| 44 | + return; |
| 45 | + } |
| 46 | + |
| 47 | + context.logger.warn( |
| 48 | + `NOTE: The "${context.builder.builderName}" builder is currently EXPERIMENTAL and not ready for production use.`, |
| 49 | + ); |
| 50 | + |
| 51 | + const normalizedOptions = await normalizeOptions(context, projectName, options); |
| 52 | + const { projectSourceRoot, workspaceRoot, runnerName } = normalizedOptions; |
| 53 | + |
| 54 | + if (runnerName !== 'vitest') { |
| 55 | + context.logger.error('Unknown test runner: ' + runnerName); |
| 56 | + |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + // Find test files |
| 61 | + const testFiles = await findTests( |
| 62 | + normalizedOptions.include, |
| 63 | + normalizedOptions.exclude, |
| 64 | + workspaceRoot, |
| 65 | + projectSourceRoot, |
| 66 | + ); |
| 67 | + |
| 68 | + if (testFiles.length === 0) { |
| 69 | + context.logger.error('No tests found.'); |
| 70 | + |
| 71 | + return { success: false }; |
| 72 | + } |
| 73 | + |
| 74 | + const entryPoints = getTestEntrypoints(testFiles, { projectSourceRoot, workspaceRoot }); |
| 75 | + entryPoints.set('init-testbed', 'angular:test-bed-init'); |
| 76 | + |
| 77 | + const { startVitest } = await loadEsmModule<typeof import('vitest/node')>('vitest/node'); |
| 78 | + |
| 79 | + // Setup test file build options based on application build target options |
| 80 | + const buildTargetOptions = (await context.validateOptions( |
| 81 | + await context.getTargetOptions(normalizedOptions.buildTarget), |
| 82 | + await context.getBuilderNameForTarget(normalizedOptions.buildTarget), |
| 83 | + )) as unknown as ApplicationBuilderInternalOptions; |
| 84 | + |
| 85 | + if (buildTargetOptions.polyfills?.includes('zone.js')) { |
| 86 | + buildTargetOptions.polyfills.push('zone.js/testing'); |
| 87 | + } |
| 88 | + |
| 89 | + const outputPath = path.join(context.workspaceRoot, 'dist/test-out', randomUUID()); |
| 90 | + const buildOptions: ApplicationBuilderInternalOptions = { |
| 91 | + ...buildTargetOptions, |
| 92 | + watch: normalizedOptions.watch, |
| 93 | + outputPath, |
| 94 | + index: false, |
| 95 | + browser: undefined, |
| 96 | + server: undefined, |
| 97 | + localize: false, |
| 98 | + budgets: [], |
| 99 | + serviceWorker: false, |
| 100 | + appShell: false, |
| 101 | + ssr: false, |
| 102 | + prerender: false, |
| 103 | + sourceMap: { scripts: true, vendor: false, styles: false }, |
| 104 | + outputHashing: OutputHashing.None, |
| 105 | + optimization: false, |
| 106 | + tsConfig: normalizedOptions.tsConfig, |
| 107 | + entryPoints, |
| 108 | + externalDependencies: ['vitest', ...(buildTargetOptions.externalDependencies ?? [])], |
| 109 | + }; |
| 110 | + extensions ??= {}; |
| 111 | + extensions.codePlugins ??= []; |
| 112 | + const virtualTestBedInit = createVirtualModulePlugin({ |
| 113 | + namespace: 'angular:test-bed-init', |
| 114 | + loadContent: async () => { |
| 115 | + const contents: string[] = [ |
| 116 | + // Initialize the Angular testing environment |
| 117 | + `import { getTestBed } from '@angular/core/testing';`, |
| 118 | + `import { BrowserTestingModule, platformBrowserTesting } from '@angular/platform-browser/testing';`, |
| 119 | + `getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting(), {`, |
| 120 | + ` errorOnUnknownElements: true,`, |
| 121 | + ` errorOnUnknownProperties: true,`, |
| 122 | + '});', |
| 123 | + ]; |
| 124 | + |
| 125 | + return { |
| 126 | + contents: contents.join('\n'), |
| 127 | + loader: 'js', |
| 128 | + resolveDir: projectSourceRoot, |
| 129 | + }; |
| 130 | + }, |
| 131 | + }); |
| 132 | + extensions.codePlugins.unshift(virtualTestBedInit); |
| 133 | + |
| 134 | + let instance: import('vitest/node').Vitest | undefined; |
| 135 | + |
| 136 | + for await (const result of buildApplicationInternal(buildOptions, context, extensions)) { |
| 137 | + if (result.kind === ResultKind.Failure) { |
| 138 | + continue; |
| 139 | + } else if (result.kind !== ResultKind.Full) { |
| 140 | + assert.fail('A full build result is required from the application builder.'); |
| 141 | + } |
| 142 | + |
| 143 | + assert(result.files, 'Builder did not provide result files.'); |
| 144 | + |
| 145 | + await writeTestFiles(result.files, outputPath); |
| 146 | + |
| 147 | + const setupFiles = ['init-testbed.js']; |
| 148 | + if (buildTargetOptions?.polyfills?.length) { |
| 149 | + setupFiles.push('polyfills.js'); |
| 150 | + } |
| 151 | + |
| 152 | + instance ??= await startVitest('test', undefined /* cliFilters */, undefined /* options */, { |
| 153 | + test: { |
| 154 | + root: outputPath, |
| 155 | + setupFiles, |
| 156 | + environment: 'jsdom', |
| 157 | + watch: normalizedOptions.watch, |
| 158 | + coverage: { |
| 159 | + enabled: normalizedOptions.codeCoverage, |
| 160 | + exclude: normalizedOptions.codeCoverageExclude, |
| 161 | + excludeAfterRemap: true, |
| 162 | + }, |
| 163 | + }, |
| 164 | + }); |
| 165 | + |
| 166 | + // Check if all the tests pass to calculate the result |
| 167 | + const testModules = instance.state.getTestModules(); |
| 168 | + |
| 169 | + yield { success: testModules.every((testModule) => testModule.ok()) }; |
| 170 | + } |
| 171 | +} |
0 commit comments