mir zu
mir zu

Reputation: 128

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

Upvotes: 9

Views: 1585

Answers (1)

martiendt
martiendt

Reputation: 2216

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

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

See the moduleNameMapper attribute in Jest configuration docs.

Upvotes: 12

Related Questions