如何在Vue 3中使用Vitest编写haveBeenCalledWith测试示例?
Vue 3 Vitest测试问题的解决办法
我之前在Vue 3项目里搞Vitest测试卡了好长时间,甚至花钱买了Udemy上的相关课程,跟着学完还是没解决问题。后来折腾了好久终于摸出一套可行的方案,分享给你:
- 版本兼容是核心:别用太新的Vitest版本,建议锁定
vitest@0.34.x和@vue/test-utils@2.4.x,新版本有时候和Vue 3的适配会出问题 - 配置文件调整:在
vite.config.ts里完善测试环境配置:import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], test: { environment: 'jsdom', // 必须指定jsdom环境,否则无法渲染Vue组件 globals: true, // 可以直接使用describe、test等全局方法,不用每次导入 coverage: { provider: 'v8', reporter: ['text', 'json', 'html'] } } }) - 全局测试前置处理:新建
tests/setup.ts文件,统一配置测试工具:import { config } from '@vue/test-utils' // 这里可以添加全局组件、指令或者mocks config.global.mocks = { $t: (key: string) => key // 比如模拟i18n的$t方法 } - 组件测试示例:写测试用例的时候,确保正确挂载组件:
import { mount } from '@vue/test-utils' import MyComponent from '../src/components/MyComponent.vue' test('renders component correctly', () => { const wrapper = mount(MyComponent, { props: { title: 'Test Title' } }) expect(wrapper.text()).toContain('Test Title') })
按照上面的步骤调整后,之前遇到的组件渲染失败、全局属性未定义、测试环境报错这些问题基本都能解决。
内容的提问来源于stack exchange,提问作者Tatyana Molchanova
相关产品推荐
相关产品推荐

