首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Jest模拟i18Next

用Jest模拟i18Next
EN

Stack Overflow用户
提问于 2021-07-02 02:06:05
回答 1查看 2.1K关注 0票数 4

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

下面是我的代码摘要:

代码语言:javascript
复制
// 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);

然后在测试失败的文件中:

代码语言:javascript
复制
import { t } from '../lib/i18next';

export function thingToTranslate() {
  t('key_1', { color: red }), // where key1 can be 'The house color is ' 
}

在这些测试中,我有以下几点:

代码语言:javascript
复制
// several imports

describe('my test', () => {
  it('does something', () ={
    expect(thingToTranslate()).toEqual('The house color is red');
  })
}

上述代码在测试中失败:

代码语言:javascript
复制
Expected: "The house color is red"
Received: "key_1"

到目前为止我尝试过的事情:

  • 嘲弄
代码语言:javascript
复制
// 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下一个医生)和我在网上找到的变体

代码语言:javascript
复制
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;

但这会产生

代码语言:javascript
复制
You are passing an undefined module! Please check the object you are passing to i18next.use()

      ## | };
      ## |
    > ## | i18n.use(initReactI18next).init({

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-03 10:09:21

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

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

代码语言:javascript
复制
i18next
  .changeLanguage('cimode')
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68218799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档