React-app-rewired: module alias cannot resolve for jest

Created on 27 Jun 2019  路  1Comment  路  Source: timarney/react-app-rewired

I create a react app with _CRA_ and add _react-app-rewired_ and _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?

Most helpful comment

Update your jest.moduleNameMapper in package.json

"jest": {
    "moduleNameMapper": {
      "^@components(.*)$": "<rootDir>/src/components$1"
      ...other modules
    }
  }

>All comments

Update your jest.moduleNameMapper in package.json

"jest": {
    "moduleNameMapper": {
      "^@components(.*)$": "<rootDir>/src/components$1"
      ...other modules
    }
  }
Was this page helpful?
0 / 5 - 0 ratings