reactjs - 如何使用 craco 为 Jest 设置别名

标签 reactjs jestjs craco

我正在构建由 create-react-app 提供的 React 应用程序。
我使用 craco 来简化配置,并为 TypeScript 和 Webpack 设置了 alise。
但是当我运行测试命令时,显示以下错误。

  • 错误信息
  •  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';
            | ^
    
    
    这是我的 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'],
      },
    };
    
    

    最佳答案

    我找到了解决方案,我更新了 package.json如下所示,它解决了这个问题。

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

    关于reactjs - 如何使用 craco 为 Jest 设置别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65767551/

    相关文章:

    reactjs - 是否可以使用 CSSTransitionGroup 根据状态以两种不同的方式进行动画处理?

    android - 类型错误 : Cannot read property 'DETECTION_MODE' of undefined - 'react-native-awesome-card-io'

    javascript - Next.js Jest 28 - 无法转换 SVG 文件

    使用状态或 Prop 进行 ReactJS 渲染

    javascript - 添加文件时状态中的重复条目

    javascript - 如何知道 React 延迟加载组件是否正常工作? react js

    reactjs - 如何用 Jest 测试 useParam() 函数

    javascript - ignoreWarnings 对 CRACO 和 webpack 5 没有影响

    tailwind-css - 如何使用 purgeCSS (Tailwindcss) 将选择器列入白名单或安全名单?

    javascript - React-testing-Library with Jest 无法解析 CRACO 别名