Vite/React/TS项目Vitest配置异常求助:断言与配置冲突
Vitest配置问题:React/TS项目中toBeVisible报错及配置冲突
测试目标
我需要让下面的测试文件正常运行:
import ErrorMessage from "./ErrorMessage"; import { render, screen } from "@testing-library/react"; it("should have hello world", () => { render(<ErrorMessage />); const message = screen.queryByText(/Hello World/i); expect(message).toBeVisible(); });
当前错误
- 测试文件报错:
Property 'toBeVisible' does not exist on type 'Assertion<HTMLElement | null>'.ts(2339)
- 在
vite.config.ts中添加test属性时,TS报错:
No overload matches this call. Object literal may only specify known properties, and 'test' does not exist in type 'UserConfigExport'
当前配置文件
vite.config.ts
/// <reference types="vitest" /> /// <reference types="vite/client" /> import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; export default defineConfig({ plugins: [react()], test: { globals: true, environment: "jsdom", css: true, setupFiles: "./src/tests/setup", }, });
注:为使用
toBeVisible()需开启css: true,但test属性引发上述TS错误。
tsconfig.json
{ "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true, "types": ["vitest/globals"] }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] }
tsconfig.node.json
{ "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true }, "include": ["vite.config.ts", "vitest.config.ts"] }
已尝试的方案
- 从
"vitest/config"导入defineConfig:解决了test属性的TS错误,但导致plugins属性出现No overload matches this call.错误。 - 拆分配置文件:创建单独的
vite.config.ts(含react插件)和vitest.config.ts(含test属性),但问题未解决。推测setupFiles未正常执行——已在./src/tests/setup.js中添加import "@testing-library/jest-dom";,目前只能在测试文件中直接导入该语句才能解决toBeVisible报错,但希望通过setupFiles全局配置实现。
求助
需要补充或调整哪些配置才能解决上述问题?
内容的提问来源于stack exchange,提问作者Muathcs
相关产品推荐
相关产品推荐

