Skip to content

bug(cdk/overlay): incompatible to non-jasmine environment in testing #22926

Closed
@lacolaco

Description

@lacolaco

Overlay is not supporting a testing environment that is not Jasmine-compatible.

See

const isTestEnvironment: boolean = typeof window !== 'undefined' && !!window &&
!!((window as any).__karma__ || (window as any).jasmine);

The isTestEnvironment flag must be true for the Overlay to be set up and tear down correctly in the test environment. This flag will only be true when running on Karma or using the Jasmine test runner.

This is unfriendly for users who use a testing tool like Jest to test Angular. Actually, until Jest v26, the default test runner was jest-jasmine2, which is a Jasmine compatible runner, so isTestEnvironment was true even for Jest. However, since Jest 27, the default test runner was changed to jest-circus, which is not Jasmine compatible, so testing of components using Overlay will fail.

Reproduction

Steps to reproduce:

  1. Clone https://github.com/lacolaco/jest-cdk-sandbox/
  2. Run yarn test:jasmine2 and it will be ok.
  3. Run yarn test:circus and it will fail.

The broken spec is below:

https://github.com/lacolaco/jest-cdk-sandbox/blob/cd65898cb907a549005e4214359fda1c12ebf179/src/app/app.component.spec.ts#L21-L33

As evidence to support this hypothesis, if I forge window.jasmine in Jest setup and pretend to be a Jasmine runner as the following workaround, this test will succeed. So this problem is not a problem with the internal workings of the new test runner, but simply a problem with the Overlay environment detection.

https://github.com/lacolaco/jest-cdk-sandbox/blob/cd65898cb907a549005e4214359fda1c12ebf179/src/setup-jest.ts#L3-L10

Object.defineProperty(window, 'jasmine', { value: true });

Expected Behavior

Keeping the same behavior as the Jasmine environment.

Actual Behavior

yarn test:circus only fails.

Environment

Angular CLI: 12.0.3
Node: 14.17.0
Package Manager: yarn 1.22.4
OS: darwin x64

Angular: 12.0.3
... animations, cdk, cli, common, compiler, compiler-cli, core
... forms, platform-browser, platform-browser-dynamic, router

Package                         Version
---------------------------------------------------------
@angular-devkit/architect       0.1200.3
@angular-devkit/build-angular   12.0.3
@angular-devkit/core            12.0.3
@angular-devkit/schematics      12.0.3
@schematics/angular             12.0.3
rxjs                            6.6.7
typescript                      4.2.4

Metadata

Metadata

Assignees

Labels

P2The issue is important to a large percentage of users, with a workaroundarea: cdk/testingregressionThis issue is related to a regression

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions