Custom Angular Test Bootstrap

Compatibility: Angular 20+ with Jasmine 5.x and Karma 6.x

As a default Angular CLI auto-generates test bootstrap via angular:test-bed-init via injecting it as a dynamic virtual module Show archive.org snapshot .

Custom Bootstrap

Override the main test option Show archive.org snapshot in angular.jsonprojects.{app}.architect.test.options.main: <test entry file> and then initialize the test environment Show archive.org snapshot :

getTestBed().initTestEnvironment(
  BrowserTestingModule,
  platformBrowserTesting(providers?),
  options?
)

Configure tsconfig.spec.json to compile the new main.ts file, e.g.:

{
  // other options like "extents":, "compilerOptions":, "include":
  "files": [
    "src/app/shared/spec/setup/main.ts"
  ],
}

Why Use a Custom Test Entry

  • Configure global test environment providers
  • Register custom Jasmine matchers and test utilities
  • Load icons, themes, and other test-wide setup
  • Replace CLI's auto-generated bootstrap with your own
  • Important: Keep TestBed options aligned with CLI defaults (strict error checking)
  • Note: Runs for every test execution, including ng test --include for individual specs

Patterns

Custom Entry Point with Strict Options

// angular.json
"test": { "options": { "main": "src/test-setup.ts" } }
// src/test-setup.ts
import { getTestBed } from '@angular/core/testing';
import { 
  BrowserTestingModule, 
  platformBrowserTesting 
} from '@angular/platform-browser/testing';

// IMPORTANT: Custom main.ts replaces CLI's auto-generated bootstrap.
// Mirror the CLI's default options to maintain strict error checking.
getTestBed().initTestEnvironment(
  BrowserTestingModule,
  platformBrowserTesting(),
  { 
    errorOnUnknownElements: true,    // Fail on unrecognized HTML elements
    errorOnUnknownProperties: true   // Fail on unrecognized element properties
  }
);

With Global Providers and Custom Setup

Keep custom enhancements (icons, matchers, themes) in separate ./imports/*.setup.ts files for better organization. Define any global providers within platformBrowserTesting.

// src/test-setup.ts
import { getTestBed } from '@angular/core/testing';
import { 
  BrowserTestingModule, 
  platformBrowserTesting 
} from '@angular/platform-browser/testing';

// Import custom enhancements using modular setup files
import './imports/icons.setup';
import './imports/theme.setup';
import './imports/jasmine-matchers.setup';

getTestBed().initTestEnvironment(
  BrowserTestingModule,
  platformBrowserTesting([
    { provide: MyService, useClass: MockMyService },
    provideHttpClient(),
  ]),
  { 
    errorOnUnknownElements: true,
    errorOnUnknownProperties: true 
  }
);
Felix Eschey