如何在Vitest中全局注册自定义插件,移除测试文件mount中的插件配置?
实现Vitest全局注册自定义插件(保留i18n本地配置)
核心思路
通过Vitest的全局setup文件预注册固定自定义插件,同时保留测试文件中i18n的独立配置能力,避免每个测试文件重复写相同的插件注册代码。
步骤1:创建全局Setup文件
在项目根目录(或指定测试工具目录)创建vitest.setup.ts,在这里注册所有需要全局生效的自定义插件:
import { config } from '@vue/test-utils' import MyCustomPlugin from '@/plugins/MyCustomPlugin' // 替换为你的插件路径 import MyCustomLoggerPlugin from '@/plugins/MyCustomLoggerPlugin' // 替换为你的插件路径 // 全局注册固定插件,带参数的插件按数组格式传入 config.global.plugins.push( MyCustomPlugin, [MyCustomLoggerPlugin, 'MyCustomParameter'] )
步骤2:配置Vitest加载全局Setup文件
修改vitest.config.ts,指定全局setup文件路径,让Vitest在所有测试执行前加载这个文件:
import { defineConfig } from 'vitest/config' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], test: { setupFiles: ['./vitest.setup.ts'], // 指向刚才创建的setup文件 environment: 'jsdom', // Vue测试需要jsdom环境 // 其他Vitest配置... } })
步骤3:简化测试文件的挂载代码
此时全局插件已经自动注册,测试文件中只需要传入当前组件专属的i18n实例即可。需要注意:直接在shallowMount中传入global.plugins会覆盖全局插件数组,因此推荐用以下两种方式处理:
方式A:手动合并(适合少量测试文件)
import { shallowMount, config } from '@vue/test-utils' import MyComponent from '@/components/MyComponent.vue' import { createI18n } from 'vue-i18n' // 当前组件专属的i18n实例 const i18n = createI18n({ locale: 'zh-CN', messages: { /* 当前组件的本地化文案 */ } }) const wrapper = shallowMount(MyComponent, { global: { // 合并全局插件与当前i18n plugins: [...config.global.plugins, i18n] }, props: { // 组件props配置 } })
方式B:封装自定义挂载函数(推荐,适合大量测试文件)
创建src/utils/test-utils.ts,封装自动合并全局插件的挂载函数:
import { shallowMount, type ShallowMountOptions, type VueWrapper } from '@vue/test-utils' import { config } from '@vue/test-utils' import type { ComponentPublicInstance } from 'vue' // 封装shallowMount,自动合并全局插件与局部插件 export function shallowMountWithPlugins<T extends ComponentPublicInstance>( component: any, options?: Omit<ShallowMountOptions<T>, 'global'> & { global?: Omit<ShallowMountOptions<T>['global'], 'plugins'> & { plugins?: ShallowMountOptions<T>['global']['plugins'] } } ): VueWrapper<T> { // 合并全局插件与测试文件传入的局部插件 const mergedPlugins = [ ...(config.global.plugins || []), ...(options?.global?.plugins || []) ] return shallowMount(component, { ...options, global: { ...options?.global, plugins: mergedPlugins } }) }
然后在测试文件中使用这个自定义函数:
import { shallowMountWithPlugins } from '@/utils/test-utils' import MyComponent from '@/components/MyComponent.vue' import { createI18n } from 'vue-i18n' const i18n = createI18n({ locale: 'zh-CN', messages: { /* 当前组件的本地化文案 */ } }) // 只需传入i18n,全局插件自动合并 const wrapper = shallowMountWithPlugins(MyComponent, { global: { plugins: [i18n] }, props: { // 组件props配置 } })
额外说明
- 如果某个测试文件需要临时禁用全局插件,可以在调用挂载函数时传入
plugins: [],此时只会加载你传入的插件; - 确保每个测试文件的i18n实例是独立创建的,避免不同测试用例之间的本地化配置相互干扰。
内容的提问来源于stack exchange,提问作者MrSpt
相关产品推荐
相关产品推荐

