Skip to main content
Version: 14.3

Test environment

In Jest, a test environment defines the sandbox context in which your tests run. For Angular projects, setting up the correct test environment is essential to ensure compatibility with the framework-specific features, such as dependency injection and change detection.

jest-preset-angular provides utility functions to simplify setting up a Jest test environment tailored for Angular projects. These functions support both zone-based and zoneless environments, catering to different testing needs.

Functions


setupZoneTestEnv(options)

Configures a test 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';

const jestConfig: Config = {
preset: 'jest-preset-angular',
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
};

export default jestConfig;

setupZonelessTestEnv(options)

Configures a test 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';

const jestConfig: Config = {
preset: 'jest-preset-angular',
setupFilesAfterEnv: ['<rootDir>/setup-jest.ts'],
};

export default jestConfig;