Next.js项目中Jest执行报错:node_modules内出现Unexpected token
npm test报SyntaxError: Unexpected token '(' 问题背景
在Next.js项目中完成以下操作后,运行npm test触发报错:
- 安装Jest相关依赖:
npm i --save-dev jest @testing-library/react @testing-library/jest-dom jest-environment-jsdom - 创建
jest.config.json配置文件,内容如下:const nextJest = require("next/jest"); const createJestConfig = nextJest({ dir: "./", }); const customJestConfig = { moduleDirectories: ["node_modules", "<rootDir>/"], testEnvironment: "jest-environment-jsdom", }; module.exports = createJestConfig(customJestConfig);
报错详情
Test suite failed to run
D:\my-project\node_modules@jest\reporters\build\GitHubActionsReporter.js:67
#getMessageDetails(failureMessage, config) { ^SyntaxError: Unexpected token '('
at Object. (node_modules/@jest/reporters/build/index.js:75:3)
当前开发依赖版本
"devDependencies": { "@testing-library/jest-dom": "^5.16.5", "@testing-library/react": "^13.4.0", "eslint": "8.14.0", "eslint-config-next": "12.1.5", "jest": "^29.0.3", "jest-environment-jsdom": "^29.0.3" }
问题原因及修复方案
1. 配置文件后缀错误
你将Jest配置文件命名为jest.config.json,但文件内容是CommonJS格式的JS代码,JSON文件无法解析这类语法,会导致配置加载异常,间接引发后续报错。
修复:
将配置文件重命名为jest.config.js,内容保持不变。
2. Next.js与Jest版本不兼容
你使用的eslint-config-next@12.1.5对应Next.js 12.1.5版本,而Jest 29.x是较新的大版本,Next.js 12对Jest 29的支持不完善。Jest 29中使用了类私有方法(即报错中的#getMessageDetails语法),但Next.js 12的默认Babel配置无法正确转译该语法,从而触发Unexpected token '('错误。
修复:
将Jest版本降级到与Next.js 12兼容的28.x版本,执行以下命令:
npm uninstall --save-dev jest jest-environment-jsdom npm install --save-dev jest@^28.1.3 jest-environment-jsdom@^28.1.3
3. 验证配置(可选)
确保jest.config.js配置符合Next.js 12要求,最终配置如下:
const nextJest = require("next/jest"); const createJestConfig = nextJest({ dir: "./", }); const customJestConfig = { moduleDirectories: ["node_modules", "<rootDir>/"], testEnvironment: "jest-environment-jsdom", }; module.exports = createJestConfig(customJestConfig);
完成以上步骤后,重新运行npm test即可解决报错。
内容的提问来源于stack exchange,提问作者sciencaholic

