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

使用Vitest+实验性ES模块时遇describe未定义及Jest JSX语法错误

问题解决:Vitest全局API未定义与Jest JSX语法支持问题

一、解决Vitest ReferenceError: describe is not defined

该错误源于Vitest默认未启用describe/it等全局测试API,按以下步骤修复:

  1. 更新Vitest配置
    在vitest.config.js的test字段中启用全局API,并添加React组件测试必需的DOM环境:
import react from '@vitejs/plugin-react';
import { defineConfig } from 'vitest/config'

export default defineConfig({
  plugins: [react()],
  test: {
    include: ['**/*.test.tsx'],
    globals: true, // 开启全局测试API
    environment: 'jsdom', // 提供DOM环境以测试React组件
  },
})
  1. 修复TypeScript类型提示
    在tsconfig.json的compilerOptions.types中添加vitest,消除类型报错:
{
  "compilerOptions": {
    // 保留原有配置
    "types": ["vitest", "@testing-library/react"]
  }
}
  1. 修正Vite配置语法错误
    你的vite.config.js末尾缺失闭合括号,导致配置失效,修正后:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'

export default defineConfig({
  plugins: [react()],
}) // 补上闭合括号

二、解决Jest SyntaxError: Support for the experimental syntax 'jsx' isn't currently enabled

Jest默认不处理JSX语法,结合你使用的SWC插件,按以下配置适配:

  1. 安装SWC Jest转换器
npm install @swc/jest --save-dev
  1. 创建Jest配置文件
    新建jest.config.js(若项目使用ES模块,可改为jest.config.mjs,或在package.json中添加"type": "module"):
export default {
  testEnvironment: 'jsdom',
  transform: {
    '^.+\\.(ts|tsx)$': '@swc/jest', // 用SWC处理TS/TSX文件
  },
  extensionsToTreatAsEsm: ['.tsx', '.ts'], // 标记TS/TSX为ES模块
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
}
  1. 调整运行命令
    在package.json的scripts中添加便捷命令:
"scripts": {
  "test:jest": "node --experimental-vm-modules node_modules/jest/bin/jest.js"
}

之后执行npm run test:jest即可运行Jest测试。

额外建议

由于你基于Vite搭建项目,优先推荐使用Vitest作为测试框架——它与Vite共享配置,无需额外适配JSX/ES模块,更轻量化且适配性更好。可考虑移除Jest和Mocha,减少依赖冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:02:27