Search code examples
reactjsjestjscraco

How to setup alias for Jest with craco


I'm building react app provided by create-react-app.

I use craco to make configuration simplify and have set up alise for TypeScript and Webpack.

But when I run test command, the following error is displayed.

  • Error Message
 spec/showMessage.test.tsx
  ● Test suite failed to run

    Cannot find module '@/components/atom/TextButton' from 'src/pages/index.tsx'

    Require stack:
      src/pages/index.tsx
      spec/showMessage.test.tsx

      3 | import styled from 'styled-components';
      4 | 
    > 5 | import { TextButton } from '@/components/atom/TextButton';
        | ^

This is my craco.config.js

  • craco.config.js
const path = require("path");

module.exports = {
  jest: {
    configure: {
      roots: ['<rootDir>/src', '<rootDir>/spec'],
      testMatch: ['<rootDir>/spec/**/*.{spec,test}.{js,jsx,ts,tsx}'],
    },
  },
  webpack: {
    alias: {
      "@": path.resolve(__dirname, "./src/"),
      "@@": path.resolve(__dirname, "./")
    },
    extensions: ['.ts', '.tsx'],
  },
};


Solution

  • I found the solution, I updated package.json like below, it solves this problem.

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