8

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

Satoru Kikuchi
  • 1,069
  • 2
  • 21
  • 33

1 Answers1

18

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

{
  "name": "xxxxx",
   :
    
  },
  "jest": {
    "moduleNameMapper": {
      "^@/(.+)": "<rootDir>/src/$1"
    }
  }
}
Satoru Kikuchi
  • 1,069
  • 2
  • 21
  • 33
  • 1
    Could you explain it? – Felipe Candal Campos Nov 05 '21 at 12:33
  • 3
    @FelipeCandalCampos In this specific instance, the left side is a regex expression which captures the remaining string after `@/` is used. The right side uses the match (through a backreference) from the capture group as a means to determine the path the user is trying to reach. – Urmzd Nov 09 '21 at 20:52