Skip to main content
Version: Next

TestBed environment

Angular provides a powerful testing utility called TestBed, which allows to configure and initialize an environment for unit testing and provides methods for creating components and services in unit tests.

jest-preset-angular provides utility functions to simplify setting up TestBed environment. These below utility functions support both zone-based and zoneless environments, catering to different testing needs.

Functions


setupZoneTestEnv(options)

Configures an environment that uses zone.js, which is the mechanism for tracking asynchronous operations. It is suitable for most Angular applications that rely on zone.js for change detection and other framework features.

You can customize the environment by providing options as function arguments.

Parameters

Example:

  • Create a Jest setup file:
setup-jest.ts
import { setupZoneTestEnv } from 'jest-preset-angular/setup-env/zone';

setupZoneTestEnv({
//...options
});
  • Update your Jest configuration:
jest.config.ts
import type { Config } from 'jest';
import presets from 'jest-preset-angular/presets';

export default {
...presets.createCjsPreset(),
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
} satisfies Config;

setupZonelessTestEnv(options)

Configures an environment that DOESN'T use zone.js, as described in Angular experimental zoneless guide. It is designed for projects that have disabled zone.js, which can lead to improved performance and simplified testing.

You can customize the environment by providing options as function arguments.

Parameters

Example:

  • Create a Jest setup file:
setup-jest.ts
import { setupZonelessTestEnv } from 'jest-preset-angular/setup-env/zoneless';

setupZonelessTestEnv({
//...options
});
  • Update your Jest configuration:
jest.config.ts
import type { Config } from 'jest';
import presets from 'jest-preset-angular/presets';

export default {
...presets.createCjsPreset(),
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
} satisfies Config;