【问题标题】:Mock i18Next with Jest用 Jest 模拟 i18Next
【发布时间】:2021-09-14 00:44:43
【问题描述】:

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

以下是我的代码摘要:

// 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');
  })
}

结果为@​​987654327@。我尝试了上述几种变体。它要么返回上一个错误(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({

我知道类似的帖子似乎有效,但正如我在这里提到的,它对我不起作用,但不知道出了什么问题

【问题讨论】:

    标签: javascript jestjs i18next


    【解决方案1】:

    您可以将cimode 作为lng 传递,而不是模拟整个库,这将使t 函数返回密钥本身。

    您需要做的就是在您的测试中调用changeLanguage

    i18next
      .changeLanguage('cimode')
    

    【讨论】:

    • 谢谢。更改语言确实会返回密钥本身,但我回到了第一个错误情况,即密钥不等于预期的翻译。有没有办法返回实际的翻译?我需要在测试中初始化 i18next 吗?
    • 测试 i18n 的最佳实践并不依赖于实际值,因为在某些公司内容中,人们编写值并可能从外部更改它们,因此,cimode 被创建为返回密钥,所以它应用对值的外部更改时不会更改。
    猜你喜欢
    • 2020-04-21
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 2019-08-17
    • 2023-04-02
    相关资源
    最近更新 更多