按Jest官方文档搭建测试环境时遇SyntaxError: Unexpected token '.'错误
运行Jest时出现
SyntaxError: Unexpected token '.'错误 环境与代码情况
- 目录结构:
learnjest/sum.js learnjest/sum.test.js learnjest/package.json learnjest/package-lock.json learnjest/node_modules
- sum.js代码:
function sum(a, b) { return a + b; } module.exports = sum;
- sum.test.js代码:
const sum = require('./sum'); test('adds 1 + 2 to equal 3', () => { expect(sum(1, 2)).toBe(3); });
- package.json配置:
{ "scripts": { "test": "jest" } }
错误信息
执行npm test命令后触发如下错误:
> @ test /path/to/learnjest > jest /path/to/learnjest/node_modules/jest/node_modules/jest-cli/build/cli/index.js:161 if (error?.stack) { ^ SyntaxError: Unexpected token '.' at wrapSafe (internal/modules/cjs/loader.js:915:16) at Module._compile (internal/modules/cjs/loader.js:963:27) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10) at Module.load (internal/modules/cjs/loader.js:863:32) at Function.Module._load (internal/modules/cjs/loader.js:708:14) at Module.require (internal/modules/cjs/loader.js:887:19) at require (internal/modules/cjs/helpers.js:74:18) at Object.<anonymous> (/path/to/learnjest/node_modules/jest/node_modules/jest-cli/build/index.js:13:12) at Module._compile (internal/modules/cjs/loader.js:999:30) at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10) npm ERR! Test failed. See above for more details. __drush_ps1: command not found __git_ps1: command not found
解决方案
这个错误的核心原因是当前使用的Node.js版本不支持ES2020引入的可选链操作符?.,而你安装的Jest新版本依赖了该语法。Node.js 14及以上版本才默认支持?.,低于此版本会触发该报错。
解决方式二选一:
- 升级Node.js版本
- 执行
node -v查看当前版本,若低于14.x,升级至14.x及以上的LTS版本,再重新运行npm test。
- 执行
- 安装兼容旧Node.js版本的Jest版本
- 卸载当前Jest:
npm uninstall jest - 安装兼容版本(如Jest 26.x,支持Node.js 10+):
npm install jest@26 --save-dev - 重新执行
npm test验证修复效果
- 卸载当前Jest:
内容的提问来源于stack exchange,提问作者arnoldbird
相关产品推荐
相关产品推荐

