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
相关产品推荐
相关产品推荐

