The Road to Next — your interactive course for Next.js with React

Babel Module Resolver with Jest

Robin Wieruch

Here you will learn how to use Jest with Babel Module Resolver for aliases that are defined in your .babelrc file:

javascript
{
  ...
  "plugins": [
    [
      "module-resolver",
      {
        "root": ["./"],
        "alias": {
          "@components": "./src/components",
          "@constants": "./src/constants",
        }
      }
    ],
  ]
}

In order to get the same alias mappings to Jest, the jest.config.js file needs to look like this:

javascript
module.exports = {
  roots: ['<rootDir>'],
  moduleFileExtensions: ['js', 'ts', 'tsx', 'json'],
  testPathIgnorePatterns: ['./node_modules/'],
  moduleNameMapper: {
    '^@components(.*)$': '<rootDir>/src/components$1',
    '^@constants(.*)$': '<rootDir>/src/constants$1',
  },
  testEnvironment: 'jsdom',
  transform: {
    '^.+\\.(js|jsx|ts|tsx)$': 'babel-jest',
  },
};

Now you can use import statemes with aliases in your Jest testing environment too.

Never Miss an Article

Join 50,000+ developers getting weekly insights on full-stack engineering and AI.

AI Agentic UI Architecture React Next.js TypeScript Node.js Full-Stack Monorepos Product Engineering
Subscribe on Substack

High signal, low noise. Unsubscribe at any time.