Reat-testing-Library with Jest doesnt resolve CRACO aliases

1.4k Views Asked by At

In my react app i use aliases with craco to organize my cmponents and imports

//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,
  },
};  

With the defined aliases:

//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;

Now if I try to run the simple App.test.jsx

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

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

I get the following Error:

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

because the import import HeadNav from "@components/layout/HeadNav"; cannot be resolved.

I tried adding the resolve aliases to my jest.config.js but i get the same error.

//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
  },
};

How can I use my defined aliases for Jest?

Thanks in Advance :)

1

There are 1 best solutions below

0
On BEST ANSWER

I was able to solve this by moving my jest config into my craco config:

//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}/$1`,
  ])
);

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