Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'],
  },
};

like image 922
Satoru Kikuchi Avatar asked Jan 25 '23 12:01

Satoru Kikuchi


1 Answers

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

{
  "name": "xxxxx",
   :
    
  },
  "jest": {
    "moduleNameMapper": {
      "^@/(.+)": "<rootDir>/src/$1"
    }
  }
}
like image 51
Satoru Kikuchi Avatar answered Mar 08 '23 10:03

Satoru Kikuchi