How to setup alias for Jest with craco
Asked Answered
D

1

9

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

Darciedarcy answered 18/1, 2021 at 0:52 Comment(0)
D
19

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

{
  "name": "xxxxx",
   :
    
  },
  "jest": {
    "moduleNameMapper": {
      "^@/(.+)": "<rootDir>/src/$1"
    }
  }
}
Darciedarcy answered 18/1, 2021 at 5:49 Comment(2)
Could you explain it?Pelvic
@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.Amharic

© 2022 - 2024 — McMap. All rights reserved.