使用Jest测试i18next工具函数时遇t不是函数错误
问题分析与解决
错误原因
你遇到的TypeError: index_1.default.t is not a function有两个核心问题:
- Jest Mock导出结构错误:原工具函数默认导入的
i18nInstance是带t方法的对象,但你在mock时把默认导出写成了函数() => i18nInstance,导致工具函数调用i18nInstance.t时,实际是在调用一个函数的t属性,自然报错。 - i18n实例未完成异步初始化:
i18next.init是异步操作,测试代码可能在实例初始化完成前就执行了localizeMessage,此时t方法还未挂载到实例上。
修复步骤
1. 修正Jest Mock的导出结构
修改localizeMessage.test.ts中的jest.mock代码,确保默认导出是测试用的i18n实例,同时添加__esModule: true兼容ES模块导出规则:
// localizeMessage.test.ts jest.mock("i18n/index", () => ({ __esModule: true, // 必须添加,处理ES模块的默认导出逻辑 default: i18nInstance, // 直接导出测试用实例,而非函数 locale: "en", }));
2. 等待i18n实例异步初始化完成
首先修改测试用的i18n实例文件,保存初始化的Promise:
// i18nForTests.ts import { createInstance } from "i18next"; import { initReactI18next } from "react-i18next"; import strings_en from "src/i18n/locales/en.json"; const i18nInstance = createInstance(); // 保存初始化Promise,不要用void丢弃 export const initPromise = i18nInstance.use(initReactI18next).init({ lng: "en", fallbackLng: "en", resources: { en: { translation: strings_en, }, }, debug: true, interpolation: { escapeValue: false, }, }); export default i18nInstance;
然后在测试文件中添加beforeAll钩子,等待初始化完成后再执行测试:
// localizeMessage.test.ts import localizeMessage from "store/utils/localizeMessage"; import i18nInstance, { initPromise } from "test/utils/i18nForTests"; jest.mock("i18n/index", () => ({ __esModule: true, default: i18nInstance, locale: "en", })); describe("localizeMessage", () => { beforeAll(async () => { await initPromise; // 等待i18n实例初始化完成 }); test("returns the correct localized string", () => { const result = localizeMessage("path.to.real.message"); expect(result).toEqual("This is a real message."); }); test("returns the correct localized string with options", () => { const result = localizeMessage("path.to.real.message.with.options", { count: "42" }); expect(result).toEqual("The answer to life, the universe, and everything is 42."); }); });
内容的提问来源于stack exchange,提问作者bildungsroman
相关产品推荐
相关产品推荐

