You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 17:05:26