Search code examples
reactjscreate-react-app

module alias cannot resolve for jest (CRA and customize-cra)


I create a react app with CRA and add react-app-rewiredand TypeScript I map some modules in tsconfig.json

{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@constants/*": ["constants/*"],
      "@components/*": ["components/*"],
      "@grid/*": ["components/Grid/*"],
      "@grid-share/*": ["components/Grid/Share/*"],
      "@utils/*": ["util/*"],
      "@services/*": ["Services/*"]
    }
  },
  "extends": "../tsconfig.json"
}

and also define them as alias modules in config-overrides.js

const path = require('path');
const { override,  addBabelPlugins } = require('customize-cra');   
module.exports = override(
  ...addBabelPlugins(
    [
      'module-resolver',
      {
        root: ["./src"],
        alias: {
          "@constants": "./src/constants",
          "@components": "./src/components",
          "@grid": "./src/components/grid",
          "@utils": "./src/util",
          "@services": "./src/Services",
          "@grid-share": "./src/components/Grid/Share"
        }
      }
    ],
  ),
);

everything is okey for yarn start but for yarn test, it cannot resolve the defined modules. what should I do for resolving the alias module for jest?


Solution

  • Okey, I found the answer. we need to define same module alias in package.json

     "jest": {
        "moduleNameMapper": {
          "@constants/(.*)": "<rootDir>/src/constants/$1",
          "@utils/(.*)": "<rootDir>/src/util/$1",
          "@grid-share/(.*)": "<rootDir>/src/components/Grid/Share/$1",
          "@grid/(.*)": "<rootDir>/src/components/Grid/$1"
        }
      },