Vue+Vitest单元测试出现document is not defined错误求助
问题解决:Vitest测试Vue组件时出现
document is not defined错误 错误原因分析
这个错误的核心是:Vitest默认运行在Node.js环境中,而Node.js没有浏览器提供的document等DOM对象。Vue组件挂载需要DOM环境支持,同时你的测试代码存在执行时机问题,导致环境未初始化就尝试挂载组件。
分步解决方案
1. 修正测试代码的执行时机
将组件挂载逻辑移到测试用例(it)或前置钩子(beforeEach)内部,避免在describe顶层执行(此时测试环境可能还未准备好),同时记得传递测试所需的props:
import { mount } from '@vue/test-utils' import HelloWorld from '../../src/components/HelloWorld.vue' describe('HelloWorld.vue', () => { it('renders props.msg when passed', () => { const msg = 'new message' // 在测试用例内部挂载组件,并传入props const wrapper = mount(HelloWorld, { props: { msg } }) expect(wrapper.text()).toMatch(msg) }) })
2. 配置Vitest使用jsdom模拟DOM环境
修改vitest.config.js,添加environment: 'jsdom'配置,让Vitest模拟浏览器的DOM环境:
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], test: { globals: true, // 启用jsdom环境,模拟浏览器DOM environment: 'jsdom' } })
3. 清理冗余依赖
你的package.json中同时存在Jest和Vitest相关依赖,二者会产生冲突,建议删除Jest系列依赖,保留Vitest相关工具即可:
{ "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "test": "vitest", "lint": "vue-cli-service lint" }, "dependencies": { "axios": "^1.6.7", "bootstrap": "^5.3.3", "bootstrap-vue": "^2.23.1", "core-js": "^3.8.3", "vue": "^3.2.13", "vue-class-component": "^8.0.0-0", "vue-router": "4", "xlsx": "^0.18.5" }, "devDependencies": { "@typescript-eslint/eslint-plugin": "^5.4.0", "@typescript-eslint/parser": "^5.4.0", "@vitejs/plugin-vue": "^5.0.4", "@vue/cli-plugin-babel": "~5.0.0", "@vue/cli-plugin-eslint": "~5.0.0", "@vue/cli-plugin-typescript": "~5.0.0", "@vue/cli-service": "^5.0.8", "@vue/eslint-config-typescript": "^9.1.0", "@vue/test-utils": "^2.4.5", "eslint": "^7.32.0", "eslint-plugin-vue": "^8.0.3", "jsdom": "^24.0.0", "typescript": "^5.4.2", "vitest": "^1.5.0" } }
完成以上三步后,重新执行测试命令npm run test即可解决问题。
内容的提问来源于stack exchange,提问作者Sergio Camilo Espinosa Botero
相关产品推荐
相关产品推荐

