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
options
(optional): An object follows TestEnvironmentOptions interface, which allows fine-tuning the environment.
Example:
- Create a Jest setup file:
- TypeScript CJS
- TypeScript ESM
import { setupZoneTestEnv } from 'jest-preset-angular/setup-env/zone';
setupZoneTestEnv({
//...options
});
import { setupZoneTestEnv } from 'jest-preset-angular/setup-env/zone/index.mjs';
setupZoneTestEnv({
//...options
});
- Update your Jest configuration:
- TypeScript CJS
- TypeScript ESM
import type { Config } from 'jest';
import presets from 'jest-preset-angular/presets';
export default {
...presets.createCjsPreset(),
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
} satisfies Config;
import type { Config } from 'jest';
import presets from 'jest-preset-angular/presets';
export default {
...presets.createEsmPreset(),
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
options
(optional): An object follows TestEnvironmentOptions interface, which allows fine-tuning the environment.
Example:
- Create a Jest setup file:
- TypeScript CJS
- TypeScript ESM
import { setupZonelessTestEnv } from 'jest-preset-angular/setup-env/zoneless';
setupZonelessTestEnv({
//...options
});
import { setupZonelessTestEnv } from 'jest-preset-angular/setup-env/zoneless/index.mjs';
setupZonelessTestEnv({
//...options
});
- Update your Jest configuration:
- TypeScript CJS
- TypeScript ESM
import type { Config } from 'jest';
import presets from 'jest-preset-angular/presets';
export default {
...presets.createCjsPreset(),
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
} satisfies Config;
import type { Config } from 'jest';
import presets from 'jest-preset-angular/presets';
export default {
...presets.createEsmPreset(),
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
} satisfies Config;