You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Next.js项目中正确配置Jest路径别名?

解决Next.js + Jest路径别名误匹配Jest内部模块的问题

你的问题出在moduleNameMapper的正则规则上:^@(.*)$会匹配所有以@开头的模块,包括Jest自身的@jest/expect这类内部依赖,导致Jest错误地试图从你的src目录下查找这些不存在的模块,从而抛出配置错误。

下面是两种可行的修复方案:

方案一:改用更具体的路径别名(推荐)

避免使用@*这种过于宽泛的匹配规则,改成针对项目目录的具体别名,既能避免冲突,也让项目结构更清晰。

修改jsconfig.json:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/components/*": ["src/components/*"],
      "@/utils/*": ["src/utils/*"],
      "@/styles/*": ["src/styles/*"]
      // 根据你的实际项目结构添加其他目录的别名
    }
  }
}

修改jest.config.js中的moduleNameMapper:

const nextJest = require('next/jest');

const createJestConfig = nextJest({
  dir: './',
});

/** @type {import('jest').Config} */
const customJestConfig = {
  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
  moduleNameMapper: {
    '^@/components/(.*)$': '<rootDir>/src/components/$1',
    '^@/utils/(.*)$': '<rootDir>/src/utils/$1',
    '^@/styles/(.*)$': '<rootDir>/src/styles/$1',
  },
};

module.exports = createJestConfig(customJestConfig);

方案二:保留@*别名,排除Jest内部模块

如果你坚持使用原有的@*别名规则,可以通过添加优先匹配项,让Jest内部模块指向正确的node_modules路径:

修改jest.config.js中的moduleNameMapper:

const nextJest = require('next/jest');

const createJestConfig = nextJest({
  dir: './',
});

/** @type {import('jest').Config} */
const customJestConfig = {
  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
  moduleNameMapper: {
    // 优先匹配Jest内部模块,指向node_modules
    '^@jest/(.*)$': '<rootDir>/node_modules/@jest/$1',
    // 匹配你的项目别名
    '^@(.*)$': '<rootDir>/src/$1',
  },
};

module.exports = createJestConfig(customJestConfig);

验证修复

修改完成后,重新运行你的Jest测试命令,检查是否还会出现找不到@jest/expect的错误,同时确认项目中使用@开头的导入语句能被正确解析。

内容的提问来源于stack exchange,提问作者tomchestnut

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 00:55:15