Using typescript with Jest does not support directly importing default exports

I developed a React application using Typescript and here is the tsconfig file I used in my project. I have no issues with importing the defaults properly as all my files include import React from 'react'.

{
  "compilerOptions": {
    "baseUrl": ".",
    "module": "esnext",
    "moduleResolution": "node",
    "outDir": "./dist/",
    "target": "es2016",
    "jsx": "react",
    "allowJs": true,
    "experimentalDecorators": true,
    "sourceMap": true,
    "noUnusedLocals": true,
    "types": ["jest"],
    "allowSyntheticDefaultImports": true,
    "paths": {
      "protractor": ["integration-tests/protractor.d.ts"]
    },
  },
  "exclude": [".yarn", "**/node_modules", "dist"],
  "include": ["**/*.js", "**/*.jsx", "**/*.ts", "**/*.tsx", "**/*.json"]
}

However, when running unit tests with Jest, I encountered an issue where Jest complained about the defaults being undefined. I am using ts-jest for transformation. Is there any configuration missing in Jest to recognize the defaults in a standard ES6 way?

To clarify, while I can import using import * as React from 'react', my preference is to use the standard ES6 import syntax like import React from 'react' instead of the typescript way.

Answer №1

By default, when using Typescript, the esModuleInterop setting is initially set to false, requiring you to import as a namespace.

To change this behavior and allow for importing without a namespace, you can set it to true in your configuration file:

tsconfig.json

{
  "allowSyntheticDefaultImports": true, // Provides typing support
  "esModuleInterop": true,
}

NOTE: After making these changes, you may need to run Jest with the option --no-cache to prevent caching of outdated configurations.

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

The data in the Angular variable is not persisting

After calling this function to retrieve an array of Articles, I noticed that the data is not being saved as expected. Take a look at my console output below. GetAll() { //return this.http.get<Array<Article>>(this.cfg.SERVER); this.http.get ...

Run a function after all xmlHttpRequests have finished executing

OVERVIEW My website relies on an API to fetch data, making multiple post and get requests to a server upon opening. While we know how long each individual call takes, determining the total time for all calls to complete is challenging. SCENARIO For inst ...

Dealing with a multi-part Response body in Angular

When working with Angular, I encountered an issue where the application was not handling multipart response bodies correctly. It seems that the HttpClient in Angular is unable to parse multipart response bodies accurately, as discussed in this GitHub issue ...

The module '*/node_modules/ngx-echarts/ngx-echarts' does not have the exported member 'Ngx Echarts Service' available for use

Initially, my Angular 6 project was functioning perfectly with all the packages in working order. However, upon attempting to upgrade it to Angular 8, I encountered the following error message when running ng serve: The module '"*/node_modules/ngx ...

Tips for correctly passing the appropriate data type using generics in TypeScript

If I have an array of objects with a key called render, which may be an optional function that takes a parameter (unknown type) const objectArray = [{a: 1}, {b: 2, render: renderFunction}, {c: 3, render: anotherFunction}] suppose the second object's ...

Retrieve the array from the response instead of the object

I need to retrieve specific items from my database and then display them in a table. Below is the SQL query I am using: public async getAliasesListByDomain(req: Request, res: Response): Promise<void> { const { domain } = req.params; const a ...

Acquire Superheroes in Journey of Champions from a REST endpoint using Angular 2

Upon completing the Angular 2 Tour of heroes tutorial, I found myself pondering how to "retrieve the heroes" using a REST API. If my API is hosted at http://localhost:7000/heroes and returns a JSON list of "mock-heroes", what steps must I take to ensure a ...

Creating a package exclusively for types on NPM: A step-by-step guide

I'm looking to set up a package (using either a monorepo or NPM) that specifically exports types, allowing me to easily import them into my project. However, I've run into some issues with my current approach. import type { MyType } from '@a ...

attempting to refine an array of objects using another array within it

I am currently filtering a group of objects in the following manner: [ { "Username":"00d9a7f4-0f0b-448b-91fc-fa5aef314d06", "Attributes":[ { "Name":"custom:organization", "Valu ...

Can you explain the purpose of typescript's tsserver?

Can you explain the role of tsserver? I understand that it assists IDEs in providing features such as error checking and auto-completion. However, I have been unable to locate any API documentation for it. ...

Struggling to extract the hours and minutes from a date in IONIC: encountering an error stating that getHours is not a recognized

I encountered an issue while trying to extract the hours and minutes from a date in Ionic. Below is the code snippet from my .html file : <ion-datetime displayFormat="HH:mm" [(ngModel)]='timeEntered1' picker-format="h:mm"></ion-date ...

Guide to connecting an object's attribute with an Angular2 form element using select

Currently facing an issue with angular forms. I am attempting to set up a form that retrieves data from a mongo collection and presents it using the <select> directive. Utilizing a FormBuilder to set it up as shown below: ngOnInit() { this.addFo ...

Is there a way to set formArray values back to their default values without using form.reset(), which sets them to null?

I am a beginner when it comes to using Angular and I am currently dealing with a form that consists of the following fields. this.catform = new FormGroup({ name: new FormControl('', Validators.required,), source: new FormControl('' ...

How can I incorporate dynamic fields into a Typescript type/interface?

In my Typescript interface, I have a predefined set of fields like this: export interface Data { date_created: string; stamp: string; } let myData: Data; But now I need to incorporate "dynamic" fields that can be determined only at runtime. This me ...

A more efficient way to specify children types in Typescript React is by directly specifying the type in the function instead

What is the reason behind this: interface UserSidebarProps { children? : React.ReactNode } function UserSidebar({children}: UserSidebarProps) { return ( <div> {children} </div> ) } Why doesn't this work? function User ...

The required property '0' is not found in the type 'any[]' but it is needed in the type '[{ post_id: string; title: string; }]'

I have gone through this post but I am still struggling to understand the issue. Why am I unable to pass this array to the update call? // create a new object with updated post properties const newPost = await this.postRepository.create(data); await thi ...

I encountered an error with Firebase when attempting to run functions on my local machine

Encountering a Firebase error when running the function locally using emulator in CLI $ firebase emulators:start --only functions Initiating emulators: ["functions"] functions: Using node@8 from host. functions: Emulator started at http://localhost:50 ...

Simulating an API endpoint using a spy service (using Jasmine)

I'm currently trying to simulate an API route within a spy service using Jasmine. Being relatively new to Angular, Typescript, and Jasmine, I find myself uncertain about where to place my code - whether it should go in the beforeEach block or in its ...

Discovering the following solution in JavaScript

I am a beginner in the field of web development and seeking help in generating a specific output for a given problem: var totalRows = 5; var result = ''; for (var i = 1; i <= totalRows; i++) { for (var j = 1; j <= i; j++) { res ...

What could be the reason behind tsx excluding attribute names with "-" in them from being checked?

Why doesn't TypeScript check attributes with a hyphen in the name? declare namespace JSX { interface ElementAttributesProperty { props:any; // specify the property name to use } } class A{ props!:{p1:string} } const tsx = <A p1="&q ...