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

Next.js 13集成Jest遇SyntaxError: Unexpected token 'export'问题求助

解决方案

这个错误是因为firestore-stripe-payments(以及它依赖的@stripe相关包)使用了ES模块语法,但Jest默认会跳过转译node_modules里的文件,导致无法识别export这类语法。你之前的transformIgnorePatterns配置逻辑弄反了——你让Jest忽略了@stripe的文件,反而应该让Jest不忽略这些包,对它们进行转译。

步骤1:修正transformIgnorePatterns配置

修改你的jest.config.js中的transformIgnorePatterns,改成以下内容:

// jest.config.js
const nextJest = require("next/jest");

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

const customJestConfig = {
  moduleDirectories: ["node_modules", "<rootDir>/"],
  moduleNameMapper: {
    "@/(.*)$": "<rootDir>/src/$1",
  },
  testEnvironment: "jest-environment-jsdom",
  // 关键修改:只忽略除@stripe和firestore-stripe-payments之外的node_modules文件
  transformIgnorePatterns: [
    "/node_modules/(?!@stripe|firestore-stripe-payments)/",
    "^.+\.module\.(css|sass|scss)$",
  ],
};

module.exports = createJestConfig(customJestConfig);

这里的(?!@stripe|firestore-stripe-payments)是正则的否定前瞻语法,意思是“只要不是@stripe或firestore-stripe-payments开头的路径,就忽略转译”,反过来就是让Jest对这两个包的文件进行转译处理。

步骤2:清理缓存并重新运行测试

有时候Jest的缓存会导致配置不生效,运行以下命令清除缓存:

npx jest --clearCache

之后重新执行你的测试命令即可。

额外排查点

如果还是报错,检查以下内容:

  • 确认next/jest版本和你的Next.js版本完全匹配,版本不兼容可能导致转译逻辑异常
  • 如果你在firebase.js中使用了ES模块的import语法,确保Jest的转译器能正确处理,必要时添加babel.config.js配置:
// babel.config.js
module.exports = {
  presets: ['next/babel'],
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 04:05:23