如何在Jest测试中传递useTranslation的t函数给工具函数?
解决React-i18next的t函数在Jest测试中传递问题
我创建了名为getFormName的工具函数,希望将react-i18next中useTranslation返回的t翻译函数作为参数传入,但在Jest测试中无法得到预期结果,请问该如何正确传递这个函数?
测试代码
import { useTranslation } from "react-i18next"; import { submissionTypes } from "../../Submissions/Details/constants"; import { getFormName } from "./helpers"; // jest.mock("react-i18next", () => ({ // useTranslation: () => ({ t: key => key }), // })); // jest.mock('react-i18next', () => ({ // useTranslation: () => ({ // i18n: { changeLanguage: jest.fn() }, // t: key => key, // }), // })); describe("utils/helpers", () => { const { t } = useTranslation(); describe("getFormName()", () => { it("should return withdrawal", () => { const result = getFormName("withdrawal", true, t ); //last parameter is 't' which is a translation function expect(result).toEqual("WITHDRAWAL"); }); }); });
getFormName函数定义
export function getFormName(type, uppercase, t) { switch (type) { case "withdrawal": return uppercase ? _.upperCase(t("mission.withdrawal")) : t("mission.withdrawal"); default: return uppercase ? _.upperCase(type) : toTitleCase(type); } }
解决方案
问题根源
你在describe块外层直接调用useTranslation(),违反了React Hook的调用规则——Hook只能在React函数组件或自定义Hook的顶层执行,Jest测试块不属于这个场景,所以无法正确拿到Mock后的t函数,甚至可能触发Hook调用错误。
两种可行的解决方式
方式一:直接模拟t函数(推荐,更简单)
既然getFormName只是接收t作为普通参数,不需要依赖React Hook环境,直接在测试用例里模拟一个符合预期的t函数即可:
describe("utils/helpers", () => { describe("getFormName()", () => { it("should return withdrawal", () => { // 自定义模拟t函数,返回对应翻译值 const mockT = (key) => { return key === "mission.withdrawal" ? "withdrawal" : key; }; const result = getFormName("withdrawal", true, mockT); expect(result).toEqual("WITHDRAWAL"); }); }); });
方式二:正确Mock react-i18next并在合适位置调用Hook
如果你需要保留Hook的调用逻辑,启用你注释掉的Mock代码,并在测试用例内部调用useTranslation(符合Hook调用规则):
// 启用Mock,放在文件最顶部 jest.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key) => { return key === "mission.withdrawal" ? "withdrawal" : key; } }), })); import { useTranslation } from "react-i18next"; import { getFormName } from "./helpers"; describe("utils/helpers", () => { describe("getFormName()", () => { it("should return withdrawal", () => { const { t } = useTranslation(); const result = getFormName("withdrawal", true, t); expect(result).toEqual("WITHDRAWAL"); }); }); });
内容的提问来源于stack exchange,提问作者shanky
相关产品推荐
相关产品推荐

