错误:您正在传递未定义的模块!请检查您传递给 i18next.use() 的对象

Sim*_*rge 3 i18next react-i18next

由于上述问题,我的单元测试失败了。

//String.ts
import * as i18n from 'i18next'
import { initReactI18next } from 'react-i18next'
import BrowserLanguageDetector from 'i18next-browser-languagedetector'
import Backend from 'i18next-http-backend'
import languageMap from '@katal/localization/webpack-loader!'

i18n
  .use(initReactI18next)
  .use(BrowserLanguageDetector)
  .use(Backend)
  .init({
    fallbackLng: 'en-US',
    load: 'currentOnly',
    detection: {
      order: ['sessionStorage', 'localStorage', 'querystring', 'navigator'],
      lookupQuerystring: 'locale',
      lookupLocalStorage: 'locale',
      lookupSessionStorage: 'locale',
      caches: [],
    },
    backend: {
      loadPath: (localeList: string[]) => languageMap[localeList[0]],
    },
    interpolation: {
      escapeValue: false,
    },
    react: {
      useSuspense: false,
    },
  })
Run Code Online (Sandbox Code Playgroud)

我嘲笑这一点的方式是:

const React = require('react')
const reactI18next = require('react-i18next')



module.exports = {
  ...reactI18next,
  // this mock makes sure any components using the translate HoC or useTranslation hook receive the t function as a prop
  useTranslation: (...args) => ({
    ...reactI18next.useTranslation(...args),
    ready: true,
    t: (tr) => tr,
  }),
}
Run Code Online (Sandbox Code Playgroud)

我将其导入到我的 App.tsx 中

import './utils/Strings'
Run Code Online (Sandbox Code Playgroud)

我检查的其他一些链接是这些这些,但它们都不起作用。任何有关解决方法的帮助都会受到赞赏

Dar*_*ega 11

我在这方面也挣扎了一段时间。我的测试很好,直到我决定在组件之外的东西上使用 i18n.t() 。笑话不喜欢这样

基于这个答案,我让它工作https://github.com/i18next/i18next/issues/1426#issuecomment-828656983

这是一个适合我的解决方案:

// setupTests.ts
jest.mock("react-i18next", () => ({
  // this mock makes sure any components using the translate hook can use it without a warning being shown
  useTranslation: () => {
    return {
      t: (str: string) => str,
      i18n: {
        changeLanguage: () => new Promise(() => {}),
      },
    };
  },
  initReactI18next: {
    type: "3rdParty",
    init: jest.fn(),
  },
}));
Run Code Online (Sandbox Code Playgroud)

编辑:没有看到 adrai 评论,他首先提到了这一点,但为了清楚起见,我将保留显示所有文件内容的答案