gpt4 book ai didi

javascript - 用 Jest 模拟 i18Next

转载 作者:行者123 更新时间:2023-12-05 00:39:20 27 4
gpt4 key购买 nike

我花了一整天的时间研究这个问题,尝试了不同的解决方案,但似乎没有任何效果。
这是我的代码的摘要:

// 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"
到目前为止我尝试过的事情:
  • mock

  • // 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__目录(来自 react-i18next docs )和我在网上找到的变体
    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({
    我知道类似的帖子似乎有效,但正如我在这里提到的,它对我不起作用,但不知道出了什么问题

    最佳答案

    您可以传递 cimode 而不是模拟整个库如lng这将使 t函数返回 key 本身。
    您需要做的就是在您的测试 调用changeLanguage .

    i18next
    .changeLanguage('cimode')

    关于javascript - 用 Jest 模拟 i18Next,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68218799/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com