Exploring the integration of Jest with TypeScript

I'm seeking guidance on how to set up TypeScript with Jest. I've scoured numerous resources but haven't found a solution that works for me.

Below is my jest.config.js:

module.exports = {
    roots: [
        '<rootDir>'
    ],
    transform: {
        "^.+\.ts$": "ts-jest"
    },
    testMatch: ['<rootDir>/tests/**/*.ts'],
    moduleFileExtensions: ['ts', 'js'],
    modulePaths: [
        '<rootDir>/src/js/'
    ],
    moduleNameMapper: {
        'Services(.*)': '<rootDir>/src/js/$1'
    },
};

The issue lies with the module name mapper, as it doesn't seem to work despite trying both modulePaths and moduleNameMapper. The error message simply states: "Cannot find module ...".

Furthermore, when attempting to mock the module name mapper (e.g.,

'i': '<rootDir>/src/js/State.ts'
) and get it functioning, I encounter an "Unexpected token export" error. This is perplexing considering I followed the guide at https://basarat.gitbooks.io/typescript/docs/testing/jest.html and have replicated the exact code from that example. Even after resorting to using Babel for Jest, the problem persists.

Despite exhaustive googling and multiple attempts, no breakthrough has been made. I've invested close to two hours in this troubleshooting process, fully aware that there ought to be a straightforward solution given the popularity of Jest and TypeScript.

Update: Listed below is my tsconfig.js file:

{
  "compilerOptions": {
    "outDir": "./dist/",
    "noImplicitAny": true,
    "module": "es2015",
    "target": "es5",
    "jsx": "react",
    "allowJs": true
  }
}

Answer №1

After reviewing the details you provided, it appears that the issue may have two components:

  1. Make adjustments to the moduleNameMapper regex.
  2. The error message 'Unexpected token export' could suggest an incorrect configuration in your tsconfig.json, such as the module setting.

1.) It is recommended to enclose 'Services(.*)' with proper regex boundaries like '^Services(.*)$'. Failing to do so might lead to unexpected errors since all matching substrings of the module name will be replaced. Additionally, consider whether you intended to use '^Services/(.*)$' (including "/") based on the alterations caused by your replacement alias.

2.) Node requires special flags to interpret ES module syntax correctly. If you are encountering this error, it likely indicates a missing transpile step from import/export to CommonJS require. Verify the module property in your tsconfig.json or test configuration to ensure it is set to "CommonJS". Remember that the default value depends on the target property:

target === "ES3" or "ES5" ? "CommonJS" : "ES6"
.

Update:

If your tsconfig.json includes baseUrl and paths alias configurations, remember to also configure the moduleNameMapper in your Jest config. While slightly redundant, ts-jest provides a helper to extract values from the TS config. Check out this example for more information.

We hope these suggestions help resolve your issue. If not, providing a complete code example would greatly assist in further troubleshooting.

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

Implementing a ReactJS component with a TypeScript interface for displaying an Alert box message using Material

I have a MUI Alert box in my application where I am trying to change the message inside with an href URL. However, when I use the herf tag, it shows as text instead of a link. How can I make it display as an actual link? In the code below, when I click th ...

ReactJS Typescript Material UI Modular Dialog Component

Hello, I need help with creating a Reusable Material UI Modal Dialog component. It's supposed to show up whenever I click the button on any component, but for some reason, it's not displaying. Here's the code snippet: *********************TH ...

The RxJS race function comes to a standstill if neither stream completes

Consider the code snippet below: import { interval, race, Subject } from 'rxjs'; import { mapTo } from 'rxjs/operators'; const a$ = new Subject<number>(); const b$ = interval(1000).pipe(mapTo(1)); race([a$, b$]).subscribe(consol ...

Attention: certain content may have been removed due to HTML sanitation

Hi there, I'm currently working on incorporating a search bar into a modal window by embedding HTML within the modal body. Here's how I've written the code: onClick() { const dialogRef = this.modal.alert() .size('lg' ...

TypeError thrown by Basic TypeScript Class

I'm encountering an issue where TypeScript is throwing a TypeError when trying to use the class Literal from file Classes.tsx in file App.tsx, even though they are in the same file. Strangely, everything works fine on typescriptlang.org/play. // Class ...

Showcasing a single object in an IONIC/Angular application using the ngIF directive

I am in need of assistance as I have encountered an issue. Essentially, I am fetching an object from an external API (Strapi) using the GET method, but when attempting to display it on Views with ngIF, it fails to show up. https://i.sstatic.net/nFyOE.png ...

Encountering Typescript issues while trying to access @angular/core packages

Recently, I made an update to my Ionic app from Angular 7 to Angular 8, and an odd error popped up: https://i.sstatic.net/icZOb.png The issue lies in the fact that I am unable to access any of the standard classes stored in the @angular/core module. This ...

I'm having trouble linking MikroORM migration to Postgresql - the npx command keeps failing. Can anyone offer some guidance on what

I am encountering a situation similar to the one described in this post. I'm following Ben Awad's YouTube tutorial: you can see where I am in the tutorial here. Objective: My goal is to execute npx mikro-orm migration:create in order to generate ...

Leveraging WebWorkers in Typescript alongside Webpack and worker-loader without the need for custom loader strings

I've been trying to implement web workers with Typescript and Webpack's worker-loader smoothly. The documentation shows an example of achieving this using a custom module declaration, but it requires the webpack syntax worker-loader!./myWorker. ...

Guide on how to create a promise with entity type in Nest Js

I am currently working on a function that is designed to return a promise with a specific data type. The entity I am dealing with is named Groups and my goal is to return an array of Groups Groups[]. Below is the function I have been working on: async filt ...

The button's status changes to disabled until I click outside the input field in Angular

I am currently facing an issue with a form (heat index calculator) that requires 2 inputs - a dropdown and a button. The button is disabled when there are no inputs or if the inputs are invalid. Everything works correctly, except for the fact that even whe ...

Routing through routers and closing modals

Within my Angular project, I am using a form component across two separate components. What I want is for the onSubmit function to close a modal if the user selects 'Save' in one component, and to navigate using the router link if it's in th ...

What sets apart a JSON Key that is enclosed in double quotes "" from one that has no quotes?

Below is my TypeScript object: { first_name:"test", last_name: "test", birthdate:"2018-01-08T16:00:00.000Z", contactNumber: "12312312312", email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e19 ...

Typescript raises a error notification regarding the absence of a semicolon when importing a JSON module

Attempting to import a local JSON object into my Vuex store using const tree = import('@/articles/tree.json');. The setting "resolveJsonModule": true, has been enabled in my tsconfig.json and it loads successfully, however NPM is flooding the out ...

Setting the initial navigation theme based on route parameters from an external source, not within the StackNavigator

Is there a way to set the initial navigation theme based on the current route params without rendering the NavigationContainer and causing a flash of content with the default theme? Can the route be accessed from outside of the NavigationContainer without ...

How can I utilize the color prop in the theme file to style new variants more comprehensively with MUI theming?

I am working on creating a custom variant for an MUI button where the color specified in the color prop should be applied as both the border and text color. While the MUI documentation offers a suggested approach, it requires addressing each available col ...

Generate ES6 prototypes using TypeScript

Is it possible to enhance specific class methods in TypeScript by making them prototypes, even when the target is ES6? Additionally, can a specific class be configured to only produce prototypes? Consider the following TypeScript class: class Test { ...

What are the recommended guidelines for using TypeScript effectively?

When facing difficulties, I have an array with functions, such as: this._array = [handler, func, type] How should I declare this private property? 1. Array<any> 2. any[] 3. T[] 4. Array<T> What is the difference in these declarations? ...

What is the reason TypeScript does not recognize the type when dealing with promises?

I am encountering an unexpected behavior where there is no error even though there should be one in TypeScript when using promises. I assigned a number value to a string variable, but surprisingly, no error was thrown. Why does this happen? https://codesa ...

Encountering "SyntaxError: Cannot use import statement outside a module" when using Jest with Vue3 and @Vueform/slider

Currently, I am using Jest as the test runner for a Vue 3 project that utilizes the @vueform slider plugin. You can find the plugin here: https://github.com/vueform/slider The code located in @vueform/slider/dist/slider.js:1 is causing a "SyntaxError: Can ...