Search code examples
reactjsjestjscraco

JEST configuration with craco


I'm building react app I use craco to make configuration simplify and have set up alise But when I run test command, the following error is displayed.

Cannot find module '@layouts/BlankLayout' from 'src/router/Router.js'

This is my craco.config.jsenter code here

const path = require('path')
 
module.exports = {
  reactScriptsVersion: 'react-scripts',
  style: {
    sass: {
      loaderOptions: {
        sassOptions: {
          includePaths: ['node_modules', 'src/assets']
        }
      }
    },
    postcss: {
      plugins: [require('postcss-rtl')()]
    }
  },
  webpack: {
    alias: {
      '@src': path.resolve(__dirname, 'src'),
      '@assets': path.resolve(__dirname, 'src/@core/assets'),
      '@components': path.resolve(__dirname, 'src/@core/components'),
      '@layouts': path.resolve(__dirname, 'src/@core/layouts'),
      '@store': path.resolve(__dirname, 'src/redux'),
      '@styles': path.resolve(__dirname, 'src/@core/scss'),
      '@configs': path.resolve(__dirname, 'src/configs'),
      '@utils': path.resolve(__dirname, 'src/utility/Utils'),
      '@hooks': path.resolve(__dirname, 'src/utility/hooks')
    }
  },
  
}

try with:

  "jest": {
    "moduleNameMapper": {
      "^@/(.+)": "<rootDir>/src/$1"
    }
  },

But it does not work


Solution

  • Jest doesn't automatically know about your webpack aliases. It needs configuring to know about them. Your moduleNameMapper looks insufficient since @layouts would map to src/@layouts instead of the desired src/@core/layouts. I suggest you change moduleNameMapper to match your aliases

     "jest": {
        "moduleNameMapper": {
          '@src/(.+)': "<rootDir>/src/$1",
          '@assets/(.+)': "<rootDir>/src/@core/assets/$1",
          '@components/(.+)': "<rootDir>/src/@core/components/$1",
          '@layouts/(.+)': "<rootDir>/src/@core/layouts/$1",
          '@store/(.+)':"<rootDir>/src/redux/$1",
          '@styles/(.+)': "<rootDir>/src/@core/scss/$1",
          '@configs/(.+)': "<rootDir>/src/configs/$1",
          '@utils': "<rootDir>/src/utility/Utils",
          '@hooks/(.+)': "<rootDir>/src/utility/hooks/$1"
        }
      },