3

I am creating tests with Jest and React Testing Library and I am having difficulties with imports to the util folder that exists within the src folder. I am using TypeScript for this which seems to create its own interesting challenges.

My jest.config.ts file looks like the following:

module.exports = {
    'preset': 'ts-jest',
    'testEnvironment': 'node',
    'testPathIgnorePatterns': [
        '<rootDir>/dist'
    ],
    'moduleNameMapper': { 'src/(.*)': '<rootDir>/src/$1' }
};

The test looks like the following:

import React from 'react';
import { render, screen } from '@testing-library/react';

import { Tag } from '/components';

describe('Tabs Component', () => {
    it('should render a tab component correctly', () => {
        render(<Tag id="test" />);

        expect(screen.getAllByTestId('test')).toHaveBeenCalled();
    });
});

When I run this I am getting import issues:

Cannot find module '/components' from 'src/components/Tag/Tag.spec.tsx'

Additionally my tsconfig looks like the following:

{
    "compilerOptions": {
        "baseUrl": "./src",
        "paths": {
            "/*": [
                "*"
            ]
        },
        "outDir": "./tested/esm",
        "module": "esnext",
        "target": "es5",
        "lib": [
            "es6",
            "dom",
            "es2016",
            "es2017"
        ],
        "jsx": "react",
        "declaration": true,
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "noUnusedLocals": true,
        "noUnusedParameters": true,
        "esModuleInterop": true,
        "noImplicitReturns": true,
        "noImplicitThis": true,
        "noImplicitAny": true,
        "strictNullChecks": true,
        "suppressImplicitAnyIndexErrors": true,
        "allowSyntheticDefaultImports": true
    },
    "include": [
        "src/**/*.spec.{ts,tsx}",
        "./jest.config.ts"
    ],
    "exclude": [
        "node_modules",
        "dist",
        "./src/**/*.stories.tsx",
        "./*.js"
    ]
}

I have tried a few of the tricks from Stack Overflow like:

Jest gives `Cannot find module` when importing components with absolute paths

None of these seemed to fix the issue.

vsync
  • 118,978
  • 58
  • 307
  • 400
Josh Bowden
  • 892
  • 3
  • 12
  • 28
  • Does this answer your question? [Jest + Typescript + Absolute paths (baseUrl) gives error: Cannot find module](https://stackoverflow.com/questions/50171412/jest-typescript-absolute-paths-baseurl-gives-error-cannot-find-module) – vsync Mar 01 '22 at 08:04
  • [Google gives a ton of answers](https://www.google.com/search?q=jest+absolute+imports), are you sure you prefer waiting for someone to answer and not simply googling it and solve it in [5 minutes](https://til.hashrocket.com/posts/lmnsdtce3y-import-absolute-paths-in-typescript-jest-tests)? – vsync Mar 01 '22 at 08:05
  • [Official Jest guide for absolute paths](https://jestjs.io/pt-BR/docs/configuration#modulepaths-arraystring) – vsync Mar 01 '22 at 08:09
  • Just the kind of response I would expect on stack overflow but I have actually tried all of those and none of them have worked for me. I tried those well before posting here. – Josh Bowden Mar 01 '22 at 11:45
  • yeah you know, it's always good to ask if OP googled or not and even **better** for OP to say so :) – vsync Mar 01 '22 at 12:25
  • You can try to create a minimal *codesandbox* demo with a single test so we could inspect the complete configuration. – vsync Mar 01 '22 at 12:35
  • " have tried a few of the tricks from Stack Overflow like:" was my way of communicating that I have done some previous searching – Josh Bowden Mar 01 '22 at 12:42
  • But Josh, I could have helped you hours ago if you would have just helped me help you by putting a *codesandbox* demo... Your question will only get pushed to the bottom of the queue if you don't act *quickly*. You might get an answer weeks or months in the future without being super active with your question and doing the maximum to assist us and solve this ASAP – vsync Mar 01 '22 at 15:43

1 Answers1

0

I think the problem here is how the import is done. As the jest.config.ts has already specified the moduleNameMapper as { 'src/(.*)': '<rootDir>/src/$1' }, it means if Tag component is imported as below,

import { Tag } from "src/components";

Jest will look into the <rootDir>/src/components/index.ts to import the Tag component.

If you want to import modules in this way,

import { Tag } from "components"; // not "/components"

It's better to replace moduleNameMapper config with moduleDirectories:

module.exports = {
    'preset': 'ts-jest',
    'testEnvironment': 'node',
    'testPathIgnorePatterns': [
        '<rootDir>/dist'
    ],
    'moduleDirectories': ['node_modules', 'src']
};

This tells Jest when it sees an import from "components", it will look into both node_modules and src and see if there is the file components/index.ts or components.ts.

PS: tsconfig.json is only used by the editor. Therefore, Jest won't take it into consideration. jest.config.ts is the config file that matters to Jest.

Tian Chen
  • 493
  • 4
  • 15