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

Vitest显式导入test时报TypeError的解决方案咨询

问题

使用Vitest搭建测试时,执行npm run test调用test()出现错误:
TypeError: Cannot read properties of undefined (reading 'test')

具体场景:

  • 测试文件显式导入import {test} from "vitest",且配置中设置globals: true时,触发该错误;
  • 注释掉显式导入语句,同时保留配置里的globals: true,错误消失;
  • 移除配置中的globals: true,仅保留显式导入import {test} from "vitest",仍出现相同错误。

需求:如何在不启用globals配置项的情况下,仅通过显式导入import {test} from "vitest"解决该错误?


代码示例

file.test.js

import { test } from "vitest";

test ("Test", () => {});

vite.config.js

/// <reference types="vitest" />
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  test: {
    globals: true,
    coverage: {
      provider: "v8",
      reporter: ["json", "html", "text"]
    },
    environment: "happy-dom"
  }
})

package.json

{
  "name": "markdown_previewer",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview",
    "test": "vitest",
    "coverage": "vitest run --coverage"
  },
  "dependencies": {
    "marked": "^12.0.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@testing-library/jest-dom": "^6.4.2",
    "@testing-library/react": "^15.0.5",
    "@testing-library/user-event": "^14.5.2",
    "@types/react": "^18.2.66",
    "@types/react-dom": "^18.2.22",
    "@vitejs/plugin-react": "^4.2.1",
    "@vitest/coverage-v8": "^1.5.3",
    "@vitest/ui": "^1.5.3",
    "eslint": "^8.57.0",
    "eslint-plugin-react": "^7.34.1",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.6",
    "happy-dom": "^14.7.1",
    "vite": "^5.2.0",
    "vitest": "^1.5.3"
  }
}

解决方案

1. 彻底禁用全局变量模式

修改vite.config.js,将test配置里的globals: true删除或设为false,确保Vitest不会注入全局的test变量,避免和显式导入的变量冲突:

test: {
  // globals: true, // 注释或删除该行,或改为globals: false
  coverage: {
    provider: "v8",
    reporter: ["json", "html", "text"]
  },
  environment: "happy-dom"
}

2. 调整导入方式,避免变量冲突

如果直接解构导入还是有问题,可以尝试导入整个Vitest模块再调用test方法,确保不会和潜在的全局变量或其他变量冲突:

import * as vitest from "vitest";

vitest.test("Test", () => {});

同时检查测试文件中是否有其他代码意外覆盖了test变量。

3. 清理依赖缓存

执行以下命令清理旧依赖和缓存,重新安装确保依赖完整性:

rm -rf node_modules package-lock.json
npm install

4. 验证版本兼容性

当前Vite 5.2.0和Vitest 1.5.3版本是兼容的,但如果问题持续,尝试升级到最新稳定版:

npm update vitest vite

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 17:37:23