Next.js项目执行npm test时Jest遇意外令牌错误求解决
Next.js中执行
npm test遇到Jest解析ESM依赖的解决方案 问题描述
在Next.js项目中执行npm test时,Jest抛出解析错误:
> npm test > adm-pos@0.1.0 test > jest FAIL __tests__/pages/Home.test.tsx ● Test suite failed to run Jest encountered an unexpected token Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax. Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration. By default "node_modules" folder is ignored by transformers. Here's what you can do: • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it. • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config. • If you need a custom transformation specify a "transform" option in your config. • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option. You'll find more details and examples of these config options in the docs: https://jestjs.io/docs/configuration For information about custom transformations, see: https://jestjs.io/docs/code-transformation Details: C:\Users\user\OneDrive\Document\slash\node_modules\mem\dist\index.js:1 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import mimicFn from 'mimic-fn'; ^^^^^^ SyntaxError: Cannot use import statement outside a module 9 | try { 10 | const response = await axiosPublic.post("api/auth/refresh", null, { > 11 | headers: { | ^ 12 | "Authorization": `Bearer ${refresh_token}` 13 | } 14 | });
查看node_modules\mem\dist\index.js文件,发现该依赖使用未转译的ESM语法:
import mimicFn from 'mimic-fn'; import mapAgeCleaner from 'map-age-cleaner';
解决方案
方法1:配置Jest转译指定依赖
Jest默认忽略node_modules目录下的文件转译,需将mem及其关联依赖加入转译白名单。
在项目的Jest配置文件(如jest.config.js或package.json的jest字段)中添加以下配置:
module.exports = { // 保留原有其他配置 transformIgnorePatterns: [ '/node_modules/(?!(mem|mimic-fn|map-age-cleaner)/)' ] };
该配置会让Jest跳过除mem、mimic-fn、map-age-cleaner之外的node_modules文件,确保这些ESM格式的依赖被转译为Jest可识别的代码。
方法2:启用Jest的ESM支持
若项目整体采用ESM规范,可直接开启Jest的ESM模式:
- 在
package.json中声明模块类型:
{ "type": "module" }
- 将Jest配置文件改为
jest.config.mjs,并添加配置:
export default { // 保留原有其他配置 extensionsToTreatAsEsm: ['.ts', '.tsx'], moduleNameMapper: { '^(\\.{1,2}/.*)\\.js$': '$1' } };
- 确保测试文件使用
import而非require语法。
方法3:降级mem包版本
若不想修改配置,可降级mem到使用CommonJS语法的旧版本,比如8.1.1版本:
npm install mem@8.1.1 --save
内容的提问来源于stack exchange,提问作者alex
相关产品推荐
相关产品推荐

