Custom Angular Test Bootstrap

Posted . Visible to the public.

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

As default Angular CLI auto-generates test bootstrap via angular:test-bed-init via injecting it as a dynamic virtual module.
Source: node_modules/@angular/build/src/builders/karma/application_builder.js:356-359

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

"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.

// 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 
  }
);
Profile picture of Felix Eschey
Felix Eschey
Last edit
Felix Eschey
License
Source code in this card is licensed under the MIT License.
Posted by Felix Eschey to makandra dev (2025-11-05 12:56)