Jest.js 模拟i18next中的t函数,使其通过键返回值

gcuhipw9  于 12个月前  发布在  Jest
关注(0)|答案(1)|浏览(112)

我需要模拟i18nextuseTranslation钩子,其中包含必须通过提供的键返回值的t函数,但我没有找到一种方法可以做到这一点。

//Here I import my translation file
import mockTranslations from './src/locales/en/translation.json';

...

// Mock react-i18next
jest.mock('react-i18next', () => ({
  ...jest.requireActual('react-i18next'),
  useTranslation: () => ({
    //Here I want to get translations, but it just returns an empty string
    t: (key: string) => mockTranslations[key],
    i18n: {
      language: 'en',
      addResourceBundle: () => jest.fn(),
      changeLanguage: () => new Promise(() => {}),
    },
  }),
}));

所以,我想通过键获得翻译值。有什么建议吗?

e5nszbig

e5nszbig1#

所以,我找到了我可以做的方式,并与你分享。在评论中,我使用这个链接(next-i18 next Jest Testing with useTranslation)得到了答案,但我必须了解它如何与TypeScript一起工作,并找到了这个一行解决方案。

jest.mock('react-i18next', () => ({
  ...jest.requireActual('react-i18next'),
  useTranslation: () => {
    const enFile = jest.requireActual('./src/locales/en/translation.json');
    return {
      t: (stringKey: string) =>
        stringKey.split('.').reduce((result, key) => result[key], enFile),
      i18n: {
        language: 'en',
        addResourceBundle: () => jest.fn(),
        changeLanguage: () => new Promise(() => {}),
      },
    };
  },
}));

希望它能帮助

相关问题