Description
openedon Sep 4, 2024
Description:
I encountered a TypeError when running Karma unit tests in an Angular project that uses the carbon-components-angular library. The error seems to occur during the afterAll phase of the tests, specifically when the focus method is called on an undefined element within the modal component.
Chrome Headless 127.0.6533.88 (Mac OS 10.15.7) ERROR An error was thrown in afterAll TypeError: Cannot read properties of undefined (reading 'focus') at http://localhost:9876/_karma_webpack_/webpack:/node_modules/carbon-components-angular/fesm2020/carbon-components-angular-modal.mjs:373:78
Steps to Reproduce
Environment:
Angular Version: 17.3.5
Carbon Components Angular Version: 5.24.3
Node Version: 18.18.0
OS: Mac OS 14.6.1
Browser: Chrome Headless 127.0.6533.88
Reproduction Steps:
Set up a basic Angular project with carbon-components-angular installed.
Add a component that utilizes the Carbon modal component.
Write Karma unit tests involving the modal component.
Run the Karma tests.
Observe the error in the console output during the afterAll phase.
Expected Behavior:
The modal component should clean up without throwing any errors in the afterAll phase of the Karma tests. The focus method should not be called on an undefined element.
Actual Behavior:
During the afterAll phase of the Karma tests, a TypeError occurs because the focus method is called on an undefined element within the modal component.
Workarounds Attempted:
Updating Packages: Attempted to update carbon-components-angular to the latest version, but the issue persists.
Mocking Focus: Tried mocking the focus() method in the tests, but the issue remains unresolved.
Manual Patch: Temporarily patched the node_modules/carbon-components-angular/fesm2020/carbon-components-angular-modal.mjs file to add a check for undefined before calling focus, which mitigated the issue.
Proposed Solution:
The issue seems to arise when the modal component attempts to call focus() on an element that may not exist. A potential fix could involve adding a guard clause to check if the element is defined before attempting to call focus().
Relevant Code Snippet
Here is the relevant code from the carbon-components-angular-modal.mjs file where the error occurs:
if (element) { element.focus(); // Add a check to ensure 'element' is not undefined }
Additional Context:
This issue blocks unit tests that involve the Carbon modal component, making it difficult to ensure the stability of the application during testing.
Request for Assistance:
I would appreciate guidance on how to handle this issue, or if this is a bug that needs to be addressed, a fix in an upcoming release.