由于上述问题,我的单元测试失败了。
//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,
},
})我嘲笑的方式是:
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,
}),
}我把这个导入到我的App.tsx中
import './utils/Strings'发布于 2022-03-19 22:32:26
我在这方面也挣扎了一段时间.在决定在组件之外的东西上使用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(),
},
}));编辑:没有看到adrai的评论,他首先提到了,但为了清楚起见,我将保留显示所有文件内容的答案
https://stackoverflow.com/questions/71532601
复制相似问题