我花了一整天的时间研究这个问题,尝试了不同的解决方案,但似乎没有什么效果。
下面是我的代码摘要:
// lib/i18next.ts
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
... (i18next initialization boilerplate)
export default i18n;
export const t = (str, options?) => i18n.t(str, options);然后在测试失败的文件中:
import { t } from '../lib/i18next';
export function thingToTranslate() {
t('key_1', { color: red }), // where key1 can be 'The house color is '
}在这些测试中,我有以下几点:
// several imports
describe('my test', () => {
it('does something', () ={
expect(thingToTranslate()).toEqual('The house color is red');
})
}上述代码在测试中失败:
Expected: "The house color is red"
Received: "key_1"到目前为止我尝试过的事情:
// several imports
jest.mock('i18next', () => ({
use: () => this,
init: () => { },
t: k => k
}));
describe('my test', () => {
it('does something', () ={
expect(thingToTranslate()).toEqual('The house color is red');
})
}TypeError: Cannot read property 'init' of undefined检查结果。我尝试了上述的几种变体。它要么返回前面的错误(Received: "key_1"),要么返回上面的错误。
我还尝试将这个文件添加到我的__mocks__目录(来自反应-i18下一个医生)和我在网上找到的变体
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
i18n
.use(initReactI18next)
.init({
lng: 'en',
fallbackLng: 'en',
// have a common namespace used around the full app
ns: ['translations'],
defaultNS: 'translations',
debug: true,
interpolation: {
escapeValue: false, // not needed for react!!
},
resources: { en: { translations: {} } },
});
export default i18n;但这会产生
You are passing an undefined module! Please check the object you are passing to i18next.use()
## | };
## |
> ## | i18n.use(initReactI18next).init({我知道类似的帖子似乎起作用,但正如我在这里提到的,它对我不起作用,但不知道出了什么问题
发布于 2021-07-03 10:09:21
您可以将cimode传递为lng,而不是模拟整个库,这将使t函数返回密钥本身。
您所需要做的就是在您的测试中调用changeLanguage。
i18next
.changeLanguage('cimode')https://stackoverflow.com/questions/68218799
复制相似问题