Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jest cannot resolve node modules subpath pattern imports

i build project using node express and using https://nodejs.org/api/packages.html#packages_subpath_patterns to prevent "../../../xxx.js"

I added this to package.json and working perfectly

"imports": {
  "#src/*": "./src/*.js"
}

But the problem when i tried to running test from jest i got this error

Cannot find module '#src/config/database.js' from 'src/database/connection.js'

    Require stack:
      src/database/connection.js
      test/admin.test.js

      1 | import { MongoClient } from "mongodb";
    > 2 | import databaseConfig from "#src/config/database.js";
        | ^


      at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:311:11)
      at Object.<anonymous> (src/database/connection.js:2:1)

I don't know how to solve this issue, tried to find solution from googling and documentation cannot find similar problem with this

like image 588
mir zu Avatar asked May 19 '26 17:05

mir zu


1 Answers

Add this in your Jest Configuration (e.g. jest.config.json)

"moduleNameMapper": {
    "#src/(.*)": "<rootDir>/src/$1"
}

See the moduleNameMapper attribute in Jest configuration docs.

like image 128
martiendt Avatar answered May 21 '26 08:05

martiendt



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!