React-testing-Library with Jest 不解析 CRACO 别名

Reat-testing-Library with Jest doesnt resolve CRACO aliases

在我的 React 应用程序中,我使用 craco 的别名来组织我的组件和导入

//craco.config.js
const path = require("path");
const alias = require("./src/config/aliases");

const SRC = "./src";
const aliases = alias(SRC);

const resolvedAliases = Object.fromEntries(
  Object.entries(aliases).map(([key, value]) => [
    key,
    path.resolve(__dirname, value),
  ])
);

module.exports = {
  webpack: {
    alias: resolvedAliases,
  },
};  

使用定义的别名:

//aliases.js
const aliases = (prefix = "src") => ({
  "@components": `${prefix}/components`,
  "@UI": `${prefix}/components/UI`,
  "@config": `${prefix}/config`,
  "@assets": `${prefix}/assets`,
  "@utils": `${prefix}/utils`,
  "@SVGs": `${prefix}/assets/SVGs`,
  "@services": `${prefix}/services`,
  "@hooks": `${prefix}/hooks`,
});

module.exports = aliases;

现在,如果我尝试 运行 简单 App.test.jsx

import { render, screen } from "@testing-library/react";
import App from "./App";

test("renders learn react link", () => {
  render(<App />);
});

我收到以下错误:

Cannot find module '@components/layout/HeadNav' from 'src/App.jsx'  

因为无法解析导入import HeadNav from "@components/layout/HeadNav";

我尝试将解析别名添加到我的 jest.config.js 但我得到了同样的错误。

//jest.config.js
const path = require("path");
const alias = require("./src/config/aliases");

const SRC = "./src";
const aliases = alias(SRC);

const resolvedAliases = Object.fromEntries(
  Object.entries(aliases).map(([key, value]) => [
    key,
    path.resolve(__dirname, value),
  ])
);

module.exports = {
  verbose: true,
  resolve: {
    alias: resolvedAliases
  },
};

如何使用我为 Jest 定义的别名?

提前致谢:)

我能够通过将我的 jest 配置移动到我的 craco 配置来解决这个问题:

//craco.config.js
const path = require("path");
const alias = require("./src/config/aliases");

const SRC = "./src";
const aliases = alias(SRC);

const resolvedAliases = Object.fromEntries(
  Object.entries(aliases).map(([key, value]) => [
  Object.entries(alias("./src")).map(([key, value]) => [
    key,
    path.resolve(__dirname, value),
  ])
);

const resolvedJestAliases = Object.fromEntries(
  Object.entries(alias("<rootDir>/src")).map(([key, value]) => [
    `^${key}/(.*)$`,
    `${value}/`,
  ])
);

module.exports = {
  webpack: {
    alias: resolvedAliases,
  },
  jest: {
    configure: {
      verbose: true,
      moduleNameMapper: resolvedJestAliases
    }
  }
};