Can moduleNameMapper ignore the imports made by a module in node_modules?

2.2k views Asked by At

How can I get the moduleNameMapper to ignore the imports that are declared inside my node_modules directory?

I have a moduleNameMapper entry that looks for src/(.*) and translates it to <rootDir>/src/$1.

However, one of my dependencies (@sendgrid/mail) happens to use imports that start with ./src/ and they break when importing them into Jest.

The jest config:

module.exports = {
    "testEnvironment": "node",
    "collectCoverage": true,
    "moduleFileExtensions": ["js", "json", "ts"],
    "roots": ["src"],
    "testRegex": ".spec.ts$",
    "coverageDirectory": "../coverage",
    "moduleDirectories": ["node_modules", "src"],
    "clearMocks": true,
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "moduleNameMapper": {
      "src/(.*)": "<rootDir>/src/$1"
    },
    "collectCoverageFrom": [
      "**/*.{js,jsx,ts,tsx}",
      "!**/*.entity.ts",
      "!**/*.dto.ts",
      "!**/*.module.ts"
    ]
  }
1

There are 1 answers

0
rbutera On BEST ANSWER

Turns out instead of using moduleNameMapper to get src/* absolute imports to work you can just use the moduleDirectories option:

// jest.config.js

const path = require("path")

module.exports = {
    "testEnvironment": "node",
    "collectCoverage": true,
    "moduleFileExtensions": ["js", "json", "ts"],
    "roots": ["src"],
    "testRegex": ".spec.ts$",
    "coverageDirectory": "../coverage",
    "moduleDirectories": ["node_modules", "src", __dirname], // <--- HERE!!!!
    "clearMocks": true,
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.{js,jsx,ts,tsx}",
      "!**/*.entity.ts",
      "!**/*.dto.ts",
      "!**/*.module.ts"
    ]
  }