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

React组件测试中Vitest配置文件引发‘Expression Expected’错误

React项目中Vitest测试报错:Expression Expected 且测试未执行

问题描述

在React项目中使用Vitest运行测试时遇到两个核心问题:

  • 测试抛出Expression Expected错误,测试文件中的console.log无输出,推测测试根本未执行
  • 移除globals: true配置后,出现expect is not defined相关错误

相关配置文件

Vite配置文件(vite.config.js)

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [react()],
    test: {
        globals:true,
        environment: "jsdom",
        setupFiles: ["./testSetup.js"],
    },
    server: {
        proxy: {
            "/api": {
                target: "http://localhost:3003",
                changeOrigin: true,
            },
        },
    },
});

testSetup.js文件

import "@testing-library/jest-dom";
import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest";

// runs a clean after each test case (e.g. clearing jsdom)
afterEach(() => {
    cleanup();
});

终端报错信息

开启globals: true时的初始报错

Error: Expression expected
 ❯ getRollupError node_modules/vitest/node_modules/rollup/dist/es/shared/parseAst.js:392:41
 ❯ convertProgram node_modules/vitest/node_modules/rollup/dist/es/shared/parseAst.js:1056:26
 ❯ parseAstAsync node_modules/vitest/node_modules/rollup/dist/es/shared/parseAst.js:1898:93
 ❯ ssrTransformScript node_modules/vitest/node_modules/vite/dist/node/chunks/dep-D8YhmIY-.js:52863:11

移除globals: true后的报错

❯ node_modules/@testing-library/jest-dom/dist/index.mjs:10:1
      8| import 'css.escape';
      9| 
     10| expect.extend(extensions);
       | ^
     11| 
 ❯ testSetup.js:3:31

已尝试的无效方案

  • 将import "@testing-library/jest-dom";替换为import "@testing-library/jest-dom/vitest";,问题依旧存在

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 21:50:05