DEV Community

Dany Paredes
Dany Paredes

Posted on • Originally published at danywalls.com on

How to Solve the "Class constructor HTMLElement cannot be invoked without 'new'" Jest Error

I'm using the Angular Testing Library to test my components, and it works exceptionally wellI love it! However, I encountered a unique situation when using a Web Component within my component. This results in the error "Class constructor HTMLElement cannot be invoked without 'new'." Typically, this issue arises when code is transpiled from ES6+ to ES5 in an environment where the custom elements specification isn't fully supported.

Install the core-js Library

The first step is to ensure that your environment has the necessary polyfills to support the class constructors for HTML elements. This is where the core-js library comes in handy. To install it, open your terminal and run:

npm install -D core-js
Enter fullscreen mode Exit fullscreen mode

The -D flag adds the package as a development dependency, ensuring its available during the build process.

Create a Polyfills File

After installing core-js, you need to create a polyfills file that will import the necessary shims. In the src folder of your library, create a file named polyfills.ts and include the following imports:

import '@webcomponents/custom-elements/src/native-shim';import '@webcomponents/custom-elements';
Enter fullscreen mode Exit fullscreen mode

These imports bring in shims for the custom elements, allowing you to use the class syntax to create elements that can be invoked with new, effectively eliminating the error.

Update jest.config.ts File

Finally, to make sure Jest is aware of these polyfills when running tests, update your jest.config.ts file in the library to include the polyfills file:

setupFiles: ['<rootDir>/src/polyfills.ts'],
Enter fullscreen mode Exit fullscreen mode

Add this line so Jest loads your polyfills before running tests. This makes the testing environment like the real one, giving you smooth testing.

Conclusion

Follow these three easy steps to fix the "Class constructor HTMLElement cannot be invoked without 'new'" error, making your custom elements work properly in various settings. I hope this helps you save time later on.

Happy coding!

Top comments (0)