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

如何在Vitest测试中获取useI18n()中的t翻译函数?

解决Vitest中测试依赖useI18n翻译函数的问题

先修复你的语法错误

你遇到的Unexpected token错误是因为解构赋值作为独立语句时必须用括号包裹,同时你的setupi18n函数写法也存在语法问题,正确写法如下:

const setupi18n = () => {
  // 正确解构useI18n返回值并返回目标属性
  const { t, d, locale } = useI18n();
  return { t, d, locale };
};

// 在beforeEach中调用时给解构语句加括号
let t;
beforeEach(() => {
  ({ t } = setupi18n());
});

不过这种写法其实没必要,结合你已经使用的vi.mock,可以直接简化获取t的逻辑。

更高效的测试方案:直接模拟t函数

你的date.strings.js中的singular和pluralize都是纯函数,逻辑完全依赖传入的t参数,根本不需要调用useI18n。直接在测试里定义一个模拟的t函数即可,无需绕弯子:

import { describe, expect, it } from "vitest";
import * as Strings from "./date.strings";

describe("pluralize", () => {
  // 模拟t函数,和你之前mock的逻辑一致:直接返回传入的key
  const mockT = (key) => key;

  it("handles plural and singular cases correctly", () => {
    expect(Strings.pluralize(3, "days", mockT)).toBe("3 days");
    expect(Strings.pluralize(1, "days", mockT)).toBe("1 day");
    
    // 可补充其他场景测试
    expect(Strings.pluralize(1, "hours", mockT)).toBe("1 hour");
    expect(Strings.pluralize(5, "minutes", mockT)).toBe("5 minutes");
  });
});

这种方式更直接,符合纯函数的测试原则——只关注输入输出,不依赖外部Vue组合式API。

如果确实需要在测试中调用useI18n(比如测试组件)

如果是测试Vue组件时需要用到useI18n,必须在Vue的setup上下文里调用,可借助@vue/test-utils的mount函数:

import { describe, expect, it } from "vitest";
import { mount } from "@vue/test-utils";
import { useI18n } from "vue-i18n";
import YourComponent from "./YourComponent.vue";

vi.mock("vue-i18n", () => ({
  useI18n: vi.fn().mockReturnValue({
    t: (key) => key
  })
}));

describe("YourComponent", () => {
  it("uses translation correctly", () => {
    const wrapper = mount(YourComponent);
    // 编写组件相关断言
  });
});

或者在测试文件的全局setup中调用(需注意和Vue的setup区分):

import { describe, expect, it, setup } from "vitest";
import { useI18n } from "vue-i18n";

vi.mock("vue-i18n", () => ({
  useI18n: vi.fn().mockReturnValue({ t: (k) => k })
}));

let t;
setup(() => {
  // 在vitest的setup上下文里调用useI18n
  const i18n = useI18n();
  t = i18n.t;
});

// 后续测试用例可直接使用t变量

内容的提问来源于stack exchange,提问作者Sinc

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 21:07:17