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

配置Jest与TypeScript时遇Unexpected token 'export'错误求助

Jest + TypeScript 配置问题:导入PocketBase时出现SyntaxError: Unexpected token 'export'

我配置Jest和TypeScript时碰到了个棘手问题,不管怎么改jest.config.js里的设置,都会反复出现同一个错误。

我的配置文件

jest.config.js

module.exports = {
  collectCoverage: false,
  moduleDirectories: ['node_modules', '<rootDir>/'],
  moduleNameMapper: {
    '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
    '^.+\\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js',
    '^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$/i': `<rootDir>/__mocks__/fileMock.js`,

    // Handle module aliases
    // Should also be updated in tsconfig.json
    "@lib/*": ["<rootDir>/app/lib/*"]
  },
  preset: 'ts-jest',
  testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
  testEnvironment: 'node',
  transform: {
    "^.+\\.tsx?$": "ts-jest"
  },
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']
}

jest.setup.ts

import '@testing-library/jest-dom/extend-expect'

测试文件

test("auth test", async () => {
  const auth = await authenticate("invaild", "password")
  expect(auth).toBe(false);
});

错误详情

错误出在authenticate函数里导入PocketBase的语句import PocketBase from "pocketbase";处,报错信息如下:

SyntaxError: Unexpected token 'export'

      4 | // This file sets up the connection to the database
      5 |
    > 6 | import PocketBase from "pocketbase";
        | ^
      7 |
      8 | export function DBConnection(): PocketBase {
      9 |   if (process.env.DB_PORT === undefined) {

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1598:14)

解决方案

这个错误根源是PocketBase是ES模块,而Jest默认的运行环境只处理CommonJS模块,导致无法识别ES模块的export语法。按以下步骤修复:

  • 修改jest.config.js,添加转换白名单
    Jest默认不会转换node_modules里的模块,但PocketBase需要被ts-jest处理,所以在配置里添加:
module.exports = {
  // ... 保留其他原有配置
  transformIgnorePatterns: ['/node_modules/(?!pocketbase)']
}

这行配置的意思是:除了pocketbase之外,其他node_modules中的模块都跳过转换。

  • 适配TypeScript模块配置
    如果你的tsconfig.json中module设置为ESNext(ES模块),需要在jest.config.js中开启ES模块支持:
module.exports = {
  // ... 保留其他原有配置
  extensionsToTreatAsEsm: ['.ts', '.tsx'],
  globals: {
    'ts-jest': {
      useESM: true
    }
  }
}

同时注意,此时你的代码中导入模块需要加上完整文件后缀(比如.ts)。

  • 核对依赖版本兼容性
    确保ts-jest和jest的版本匹配,比如ts-jest@29必须搭配jest@29。可以运行npm list jest ts-jest查看版本,不兼容的话升级到对应匹配版本即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 14:20:40