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

Jest遇意外令牌错误(TypeScript):多配置尝试仍未解决

解决Jest "encountered an unexpected token" 错误及后续ReferenceError问题

我在使用Jest时遇到了Jest encountered an unexpected token错误,尝试多套配置仍未彻底解决,具体情况如下:

现有配置文件

tsconfig.json

{
  "extends": "@tsconfig/node18",
  "compilerOptions": {
    "outDir": "./dist/lib",
    "inlineSourceMap": true,
    "inlineSources": true,
    "experimentalDecorators": true
  },
  "exclude": ["cdk.out", "build", "node_modules", "dist"]
}

jest.config.js(初始配置)

module.exports = {
  testMatch: ['**/*.test.js'],
  preset: 'ts-jest',
  testEnvironment: 'node',
};

babel.config.js

module.exports = {
  presets: [['@babel/preset-env', { targets: { node: 'current' } }], '@babel/preset-typescript'],
};

尝试过的无效配置

  1. 该配置解决了解析错误,但另一测试文件出现ReferenceError: BWTC is not defined:
module.exports = {
  testMatch: ['**/*.test.js'],
  preset: 'ts-jest',
  testEnvironment: 'node',
  transform: {
    '^.+\\.(ts|tsx)?$': 'ts-jest',
    '^.+\\.(js|jsx)$': 'babel-jest',
  },
  transformIgnorePatterns: [],
};
  1. 其他未解决初始错误的配置:
module.exports = {
  testMatch: ['**/*.test.js'],
  preset: 'ts-jest',
  testEnvironment: 'node',
  transformIgnorePatterns: ['node_modules/(?!(.*\\.mjs$|pdfjs-dist))'],
};
module.exports = {
  testMatch: ['**/*.test.js'],
  preset: 'ts-jest',
  testEnvironment: 'node',
  transform: {
    '^.+\\.(js|ts|tsx)$': 'ts-jest',
  },
};

原始错误信息

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.


问题分析与解决方案

1. 解决"unexpected token"错误

这个错误通常是Jest未转译使用ES模块/非标准语法的文件(尤其是node_modules内的依赖),或是ts-jest与babel-jest配置冲突导致。

优化配置方案

放弃混合使用ts-jest和babel-jest,统一用ts-jest处理所有TypeScript/JavaScript文件,同时指定需要转译的node_modules依赖:

module.exports = {
  testMatch: ['**/*.test.js'],
  preset: 'ts-jest',
  testEnvironment: 'node',
  transform: {
    '^.+\\.(ts|tsx|js|jsx)$': 'ts-jest',
  },
  // 按需添加需要转译的node_modules包,比如示例中的pdfjs-dist
  transformIgnorePatterns: [
    'node_modules/(?!(pdfjs-dist|其他需要转译的包名))',
  ],
  // 确保ts-jest使用项目的tsconfig配置
  globals: {
    'ts-jest': {
      tsconfig: './tsconfig.json',
    },
  },
};

配置说明:

  • 统一转译引擎避免冲突,用ts-jest处理所有文件
  • transformIgnorePatterns精准控制node_modules的转译范围,只转译需要的依赖
  • 显式绑定tsconfig路径,确保TypeScript规则生效

2. 解决ReferenceError: BWTC is not defined

这个错误主要有两种成因,对应解决方案如下:

  • BWTC为全局变量但未注入测试环境:在jest配置中添加初始化文件,提前注入全局变量:

    // jest.config.js
    module.exports = {
      // ...其他配置
      setupFiles: ['./jest.setup.js'],
    };
    

    创建jest.setup.js文件:

    global.BWTC = require('path/to/bwtc-module'); // 根据实际模块路径调整
    
  • BWTC导入方式错误:检查测试文件的导入语句是否与模块导出方式匹配:

    // 若为默认导出
    import BWTC from 'bwtc-package';
    // 若为命名导出
    import { BWTC } from 'bwtc-package';
    

额外检查项

  • 确认依赖版本兼容:ts-jest、typescript、jest版本需适配Node.js 18环境,可参考ts-jest官方文档的版本匹配表
  • 排查测试文件语法错误:比如未闭合的括号、错误的文件路径等
  • 若使用ES模块(import/export),需在package.json中设置"type": "module",或在jest配置中启用extensionsToTreatAsEsm

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 00:26:12