DEV Community

Cover image for Jest with TypeScript and aliased imports (custom paths)
Emmanouil Liakos
Emmanouil Liakos

Posted on

16

Jest with TypeScript and aliased imports (custom paths)

In this post we are going to setup jest for a TypeScript project with custom aliases (path mapping) support. If you haven't read my previous post about cleaner imports in TypeScript using aliases, you can do that here. It's pretty cool that we can use the same aliases in our tests to keep them nice and clean ✨

We are going to use yarn package manager. However, there are no differences with npm - other than the commands themselves.

Install Jest

  • Run yarn add --dev jest.

Add TS support

  • Add type support: yarn add --dev @types/jest
  • Install ts-jest. It's a custom jest transformer that will help us use Jest with TypeScript.
  • Run yarn jest --init to initialize a config file. Answer the questions as you wish (ask Yes for TS support).
  • Go to your tsconfig and "@types/jest" inside types array:
{
...,
"types": [..., "@types/jest"],
...
}
Enter fullscreen mode Exit fullscreen mode

Add path support

  • Make sure you have at least the following config in jest.config.ts:
import { pathsToModuleNameMapper, JestConfigWithTsJest } from "ts-jest";
import { compilerOptions } from "./tsconfig.paths.json";

const jestConfig: JestConfigWithTsJest = {
  preset: "ts-jest",
  moduleDirectories: ["node_modules", "<rootDir>"],
  moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths)
 }

export default jestConfig;
Enter fullscreen mode Exit fullscreen mode

Here we import our custom paths defined in tsconfig.paths.json (for more info on this read here):

import { compilerOptions } from "./tsconfig.paths.json";
Enter fullscreen mode Exit fullscreen mode

The moduleDirectories prop did the trick for me. Also make sure to remove comments from both jest.config and tsconfig, since they sometimes cause parsing errors. Hope this helped someone 😎

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (1)

Collapse
 
jbo profile image
Julien Boulay

Thank you @mliakos for this tips.

I make it work with pathsToModuleNameMapper(compilerOptions.paths, { prefix: '<rootDir>/' }) because adding <rootDir> to moduleDirectories generates many typescript compilation failures on my project.

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay