Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not locate module - jest with esm nodejs app

I'm trying to write tests for my express endpoints, but I'm having troubles importing express with jest.

My package.json has "type": "module", set and my tsconfig looks as follows:

{
  "compilerOptions": {
    "module": "ES2020",
    "target": "ES2020",
    "esModuleInterop": true,
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "./dist"
  },
  "include": [
    "src"
  ]
}

I have to import files providing the .js extension, otherwise the console yells at me that modules cannot be found, eg.

import {validateToken} from "../registration/validate.js";

It breaks jest of course, so I use moduleNameMapper. Here is my jest config:

  "jest": {
    "setupFiles": [
      "<rootDir>/src/test.setup.ts"
    ],
    "testRegex": "src/.*\\.test\\.(t|j)sx?$",
    "transform": {
      "\\.[jt]sx?$": "ts-jest"
    },
    "globals": {
      "ts-jest": {
        "useESM": true
      }
    },
    "moduleNameMapper": {
      "(.+)\\.js": "$1"
    },
    "extensionsToTreatAsEsm": [
      ".ts"
    ]
  }

Unfortunately it results in broken imports for express dependencies:

    Configuration error:
    
    Could not locate module ipaddr.js mapped as:
    $1.
    
    Please check your configuration for these entries:
    {
      "moduleNameMapper": {
        "/(.+)\.js/": "$1"
      },
      "resolver": undefined
    }

    > 1 | import express from "express";
        | ^
      2 | import cors from "cors";
      3 | import dotenv from "dotenv";
      4 | import {Server, createServer} from "http";

      at createNoMappedModuleFoundError (node_modules/jest-resolve/build/resolver.js:759:17)
      at Object.<anonymous> (node_modules/proxy-addr/index.js:24:14)
      at Object.<anonymous> (node_modules/express/lib/utils.js:22:17)
      at Object.<anonymous> (node_modules/express/lib/application.js:24:19)
      at Object.<anonymous> (node_modules/express/lib/express.js:18:13)
      at Object.<anonymous> (node_modules/express/index.js:11:18)
      at Object.<anonymous> (src/app.ts:1:1)

like image 221
Siepraa Avatar asked Oct 19 '25 00:10

Siepraa


1 Answers

Ok, I finally figured it out. It may not be perfect but it works. @Mike 'Pomax' Kamermans was right, but there was a missing part:

  1. The test command should look like this "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest"
  2. The transform prop needed a little adjustment
"transform": {
  "\\.[jt]sx?$": [
    "ts-jest",
    {
      "useESM": true <<< here
    }
  ]
},

The rest is all about pointing jest to built files, instead of letting it to compile them by itself

like image 59
Siepraa Avatar answered Oct 21 '25 14:10

Siepraa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!