Vue3项目Vitest测试报错:ReferenceError: location is not defined
解决Vitest测试中
location is not defined的问题 问题根源
createWebHashHistory()依赖浏览器环境的location全局对象,但Vitest默认运行在Node.js环境中,不存在这个浏览器专属对象,因此触发报错。
调试与解决要点
全局启用浏览器环境模拟
在vitest.config.js中配置使用jsdom环境,它会模拟完整的浏览器全局对象(包括location):import { defineConfig } from 'vitest/config' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], test: { environment: 'jsdom', globals: true // 可选:让window、location等全局变量无需导入直接使用 } })局部模拟location对象
如果不想全局启用jsdom,可以在单个测试文件的开头或beforeAll钩子中手动模拟:beforeAll(() => { global.location = { hash: '', pathname: '/', // 按需添加其他location属性 } })隔离组件与真实路由
测试独立组件时,无需引入完整路由实例,通过模拟路由依赖避免环境问题:import { shallowMount } from '@vue/test-utils' import MyComponent from '@/components/MyComponent.vue' test('组件渲染正常', () => { const wrapper = shallowMount(MyComponent, { global: { mocks: { $route: { path: '/' }, $router: { push: vi.fn() } } } }) expect(wrapper.exists()).toBe(true) })动态切换路由历史模式
在路由文件中根据环境判断使用不同的历史模式,测试环境用不依赖location的createMemoryHistory:// src/router/index.js import { createRouter, createWebHashHistory, createMemoryHistory } from 'vue-router' const router = createRouter({ history: import.meta.env.VITEST ? createMemoryHistory() : createWebHashHistory(), routes, // 其他路由配置 }) export default router
内容的提问来源于stack exchange,提问作者piccy
相关产品推荐
相关产品推荐

