Vitest报错$setup.t is not a function:Vue3+TS+vue-i18n单元测试问题
解决Vue3 + vue-i18n单元测试中
t is not a function的问题 先明确组件中t的来源
先确认你的Example.vue里t的引入方式,对应不同方案:
- 情况1:在
<script setup>中直接通过useI18n获取 - 情况2:通过自定义hooks(如
src/i18n/hooks/helper.ts)封装调用 - 情况3:使用全局
$t(模板或选项式API中直接调用)
对应解决方案
情况1:直接用useI18n的t
在测试文件中mock vue-i18n的useI18n函数,让它返回包含t的对象:
// Example.spec.ts import { shallowMount } from '@vue/test-utils' import Example from './Example.vue' import { useI18n } from 'vue-i18n' // mock useI18n vi.mock('vue-i18n', () => ({ useI18n: () => ({ t: (key: string) => key // 可根据测试需求自定义返回值 }) })) describe('Example.vue', () => { it('renders correctly', () => { const wrapper = shallowMount(Example) expect(wrapper.exists()).toBe(true) }) })
情况2:用了自定义hooks(如helper.ts)
如果t来自自定义hooks封装,比如helper.ts代码如下:
// src/i18n/hooks/helper.ts import { useI18n } from 'vue-i18n' export const useTranslation = () => { const { t } = useI18n() return { t } }
直接mock这个自定义hooks即可:
// Example.spec.ts import { shallowMount } from '@vue/test-utils' import Example from './Example.vue' import { useTranslation } from '@/i18n/hooks/helper' // mock自定义hooks vi.mock('@/i18n/hooks/helper', () => ({ useTranslation: () => ({ t: (key: string) => `translated-${key}` }) })) describe('Example.vue', () => { it('renders translated content', () => { const wrapper = shallowMount(Example) expect(wrapper.text()).toContain('translated-some-key') }) })
情况3:使用全局$t
如果组件模板用了$t('key')或选项式API用this.$t,在shallowMount的全局配置中添加mock:
// Example.spec.ts import { shallowMount } from '@vue/test-utils' import Example from './Example.vue' describe('Example.vue', () => { it('renders correctly', () => { const wrapper = shallowMount(Example, { global: { mocks: { $t: (key: string) => key } } }) expect(wrapper.exists()).toBe(true) }) })
注意事项
- 若使用Vitest用
vi.mock,Jest则用jest.mock - 组件同时用多种
t调用方式时,需对应mock所有来源 - 可根据测试断言需求,自定义
t的返回值
内容的提问来源于stack exchange,提问作者AlbertGmzL
相关产品推荐
相关产品推荐

