It appears that Jest is having trouble comprehending the concept of "import type"

We've just completed a major update to our monorepository, bringing it up to date with the following versions:

  • Nx 14.3.6
  • Angular 14.0.3
  • Jest 28.1.1
  • TypeScript 4.7.4

Although the compilation process went smoothly after the upgrade, we encountered numerous runtime errors such as "emitDecoratorMetadata causes runtime errors by referencing type-only imports with namespaces" (https://github.com/microsoft/TypeScript/issues/42624). This issue was also flagged by ESLint.

To address this, we had to replace all "import" statements with "import type" for types and interfaces across the board. This resolved the runtime errors and restored the functionality of the application. Additionally, to resolve the ESLint error, we installed and utilized the "eslint-plugin-import" extension.

However, this fix led to a new problem - our tests stopped functioning properly. It appears that Jest does not recognize the "import type" statement. In every unit test for a class utilizing "import type", the tests failed with the error:

ReferenceError: Zyz is not defined

(where xyz represents an imported type in the tested class, e.g.

// some-component.ts
import type { Xyz } from '...';
...

If we remove the "type" keyword from the "import type" statement, the tests run successfully but the earlier runtime errors resurface.

I have conducted thorough research (primarily focusing on babel usage/reconfiguration) based on findings from posts like this one: https://github.com/babel/babel/issues/10981, yet I am still grappling with solving this issue.

Answer №1

Looks like the issue is resolved by following the workaround provided here: https://github.com/thymikee/jest-preset-angular/issues/1199#issuecomment-1168802943

To fix this in tsconfig.spec.json, update the "include" property to include all typescript files:

// tsconfig.spec.json
{
  ...
  "include": ["**/*.ts"]
}

Prior configuration was:

// tsconfig.spec.json
{
  ...
  "include": ["**/*.spec.ts", "**/*.test.ts", "**/*.d.ts", "jest.config.ts"]
}

Edit: Besides the above adjustments, it appears that ts-jest also needs non-isolatedModules. We had set isolatedModules: true before, which led to issues with type-only imports.

If anyone has insights on why or a better solution, please share your thoughts.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

There is no overload that fits this call (regarding a basic array retrieved from an api)

While attempting to utilize a .map function on a simple array (['a','b','c']) fetched using the useEffect hook, I encountered an error in TypeScript. The array elements rendered correctly when the code was executed and no erro ...

Error: Promises must be managed correctly

I've been working on a timer-based function that is supposed to run once a week and create almost identical copies of existing documents. However, every time I try to execute it, I encounter the error message "Promises must be handled appropriately." ...

Learning how to merge two observable streams in Angular2 by utilizing RxJS and the powerful .flatMap method

Within my Angular2 app, I have created an Observable in a Service called ContentService. Here is a simplified version of the code: @Injectable() export class ContentService { constructor(private http:Http, private apiService:ApiService) { th ...

Ensure that TypeScript compiled files are set to read-only mode

There is a suggestion on GitHub to implement a feature in tsc that would mark compiled files as readonly. However, it has been deemed not feasible and will not be pursued. As someone who tends to accidentally modify compiled files instead of the source fil ...

Unable to choose Typescript as a programming language on the VSCode platform

Recently, I encountered an issue while using Visual Studio Code with TypeScript. Even though TypeScript is installed globally, it is not showing up in the list of file languages for syntax highlighting. Despite trying various troubleshooting methods such a ...

Quicker component refreshing in the Angular framework

Two Angular components were created, one for adding a new post and another for displaying all posts. Clicking the create post button redirects to the PostList component, which shows all posts. To automatically load the new post without manual refreshing, w ...

Shifting the Ion Menu side dynamically based on screen size: A step-by-step guide

Working with Ionic 4, I encountered the need to dynamically change the side property of ion-menu. On larger screens, ion-menu is always visible or static, whereas on smaller screens, it remains hidden until the user clicks on the ion-menu-button. My goal i ...

Angular and Bootstrap 5 combine to create a dynamic multi-item carousel featuring animated slide transitions and embedded YouTube videos

I'm trying to create a multi-item carousel using YouTube videos, and although I have managed to get it working with Bootstrap 5 carousel and cards, the animation when the carousel slides is not as smooth as I would like. The issue seems to be that the ...

How can I effectively make properties accessible in my template to facilitate form validation in Angular?

Scenario: I'm facing a situation in my Angular project where I have a LoginFormComponent. This component has a form with two properties: email and password. My goal is to create properties within this component that can be accessed in the template. Th ...

"Encountering issues when trying to retrieve a global variable in TypeScript

Currently facing an issue with my code. I declared the markers variable inside a class to make it global and accessible throughout the class. However, I am able to access markers inside initMap but encountering difficulties accessing it within the function ...

Angular IIFE functions being executed prior to the DOM being fully loaded

Currently, I am working on building an application with angular 6. In my project, there is a JavaScript framework file that includes some common event binding logic implemented as Immediately Invoked Function Expressions (IIFE). The issue I am facing is t ...

The Google Books API has reached its limit for requests

Encountering a rate limit exceeded error from the Google Books API while using this demo: To reproduce, open the developer console in Chrome and perform some searches. The rate limit errors will be displayed in the console. [],"lazyUpdate":null},"status" ...

Struggling to integrate authentication and authorization features into a ReactJS application with Microsoft Azure AD or Database login functionality

We have an application built on React v18 with a backend that includes a Web API and SQL Server database. Our requirement is to authenticate and authorize users using either MS Azure AD or the database. If a user attempts to log in with a username and pas ...

Make an http.patch request to the server using a Nativescript application

I am attempting to make an http.patch request to the server in my Nativescript application, which is built with Typescript and Angular2. The backend system is developed using Python(Django). Here is the code for my request: updateOrder(id, message) { ...

Display fresh information that has been fetched via an HTTP request in Angular

Recently, I encountered an issue where data from a nested array in a data response was not displaying properly in my component's view. Despite successfully pushing the data into the object programmatically and confirming that the for loop added the it ...

The properties required by the type for typescript reactjs are not present

I've come across an array with the following structure: export const SideBarTags = [ { name: 'Tutorials', link: '../tutorials', icon: faFileAlt, dropdownItems: null, active: false, }, { name: 'An ...

What are the best ways to implement advanced data filtering in JavaScript?

Is there a way to improve the filtering of data in the ngx-datatable? Currently, I have a filter that only works for the "Name" column. How can I adjust it to filter data from other columns like "id" or "phone" as well? filt ...

Error: Could not locate application for Ionic Serve command

I have been developing a project in Ionic2 on another computer. However, when I try to run ionic serve on my PC, an error message appears: 192.168.1.100:8100 Application not found I have configured my app to use a static IP address... How can I resolve ...

Utilizing Typescript for Efficient Autocomplete in React with Google's API

Struggling to align the types between a Google address autocomplete and a React-Bootstrap form, specifically for the ref. class ProfileForm extends React.Component<PropsFromRedux, ProfileFormState> { private myRef = React.createRef<FormContro ...

Restarting an Angular app is necessary once its HTML has been updated

I've encountered an interesting challenge with an application that combines MVC and Angular2 in a not-so-great way. Basically, on the Index page, there's a partial view loading the Angular app while also including all the necessary JavaScript li ...