Configuring Jest to render a component with alias

I'm using Jest with Testing Library on TypeScript. When I try to use the render function (from Testing Library) to load a component with this type of import, for example:

import backgroundImage from '@/public/background-login.jpg';
import FormArea from '@/components/FormContainer';
import Input from '@/components/Input';
import Button from '@/components/Button';

it says:

Cannot find module '@/public/background-login.jpg' from 'src/app/login/page.tsx'

When I do like below it works:

import backgroundImage from './../../public/background-login.jpg';
import FormArea from './../../components/FormContainer';
import Input from './../../components/Input';
import Button from './../../components/Button';

My tsconfig.json:

    "baseUrl": ".",
    "paths": {
      "@/*": [
        "./src/*"
      ]
    }

My jest.config.ts (trying to do something):

import type { Config } from "@jest/types";

const config: Config.InitialOptions = {
  preset: "ts-jest",
  moduleNameMapper: {
    "^@/(.*)": "<rootDir>/$1",
    "@/(.*)": "<rootDir>/$1",
    "@/public/(.*)": "<rootDir>/public/$1",
    "^@/public/(.*)": "<rootDir>/public/$1",
    "@/components/(.*)": "<rootDir>/components/$1",
    "^@/components/(.*)": "<rootDir>/components/$1",
  },
  rootDir: "./src",
  roots: ["<rootDir>"],
  testEnvironment: "jsdom",
}

export default config;

How can I solve this?

Upvotes: 0

Views: 25

Answers (0)

Related Questions