diff --git a/packages/angular/build/src/builders/unit-test/builder.ts b/packages/angular/build/src/builders/unit-test/builder.ts index f103b6ddc8af..e86895fdf579 100644 --- a/packages/angular/build/src/builders/unit-test/builder.ts +++ b/packages/angular/build/src/builders/unit-test/builder.ts @@ -142,15 +142,28 @@ export async function* execute( 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';`, `import { beforeEach, afterEach } from 'vitest';`, '', + 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));`, '', - `getTestBed().initTestEnvironment(BrowserTestingModule, platformBrowserTesting(), {`, + `@NgModule({`, + ` providers,`, + `})`, + `export class TestModule {}`, + '', + `getTestBed().initTestEnvironment([BrowserTestingModule, TestModule], platformBrowserTesting(), {`, ` errorOnUnknownElements: true,`, ` errorOnUnknownProperties: true,`, '});', diff --git a/packages/angular/build/src/builders/unit-test/options.ts b/packages/angular/build/src/builders/unit-test/options.ts index 6bfe7361eebb..9edd02d1c14a 100644 --- a/packages/angular/build/src/builders/unit-test/options.ts +++ b/packages/angular/build/src/builders/unit-test/options.ts @@ -52,6 +52,7 @@ export async function normalizeOptions( reporters, browsers, watch, + providersFile: options.providersFile && path.join(workspaceRoot, options.providersFile), }; } diff --git a/packages/angular/build/src/builders/unit-test/schema.json b/packages/angular/build/src/builders/unit-test/schema.json index 223aa149bcdf..8cc91c7d8b90 100644 --- a/packages/angular/build/src/builders/unit-test/schema.json +++ b/packages/angular/build/src/builders/unit-test/schema.json @@ -65,6 +65,11 @@ "items": { "type": "string" } + }, + "providersFile": { + "type": "string", + "description": "TypeScript file that exports an array of Angular providers to use during test execution. The array must be a default export.", + "minLength": 1 } }, "additionalProperties": false,