---
title: "How to Solve the \"Class constructor HTMLElement cannot be invoked without 'new'\" Jest Error"
date: "2023-11-11"
slug: "how-to-test-custom-elements-with-angular-testing-library"
author: "Dany Paredes"
canonical: "https://danywalls.com/how-to-test-custom-elements-with-angular-testing-library"
description: "I'm using the Angular Testing Library to test my components, and it works exceptionally well—I love it! However, I encountered a unique situation when using a Web Component within my component. This results in the error \"Class constructor HTMLElement..."
---

I'm using the Angular Testing Library to test my components, and it works exceptionally well—I 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:

```bash
npm install -D core-js
```

The `-D` flag adds the package as a development dependency, ensuring it’s 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:

```typescript
import '@webcomponents/custom-elements/src/native-shim';
import '@webcomponents/custom-elements';
```

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:

```typescript
setupFiles: ['<rootDir>/src/polyfills.ts'],
```

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!

