5

我有一个 react 项目,我已经包含了 i18next = 15.0.4 和 react-i18next = 10.2.0 依赖项。我已经创建了一个使用 react-i18next 初始化 i18next 的模块,并且我正在尝试使用 Jest 对该代码进行单元测试。

我尝试导入初始化 i18next 的 i18n 模块并使用 jest 对其进行单元测试。

这是我的 i18n.ts 模块

import i18next from "i18next";
import { initReactI18next } from "react-i18next";

const config = {
    resources: {
        en: {
            static: {},
        },
    },
    fallbackLng: "en",
    defaultNS: "static",
    ns: "static",
    interpolation: {
        prefix: "[",
        suffix: "]",
    },
};

i18next.use(initReactI18next).init(config);

export default i18next;

我试图从我的测试代码中调用它(i18n.test.ts):

import i18n from "./i18n";

describe("i18n", () => {

    it("should work fine", () => {
        const strings = {
            key: "value",
        };
        i18n.addResourceBundle("en", "static", strings, true, true);
    });
});

我希望这个测试能够通过,但是我得到了以下错误:

TypeError: Cannot read property 'type' of undefined
      at I18n.use (node_modules/i18next/dist/commonjs/i18next.js:257:18)

这基本上指出了 i18next.js 中的这段代码

    value: function use(module) {
      if (module.type === 'backend') {
        this.modules.backend = module;
      }

我该如何解决这个问题?

4

5 回答 5

6

尝试这个:

const reactI18nextModule = require("react-i18next");

代替

import { initReactI18next } from "react-i18next";

在这里阅读更多关于 require vs import 的笑话测试:

开玩笑模拟默认导出 - 需要与导入

希望能帮助到你 :)

于 2019-06-24T08:59:55.273 回答
3

您很可能遵循了本指南: https ://react.i18next.com/misc/testing

它说你应该使用这个模拟:

jest.mock('react-i18next', () => ({
  // this mock makes sure any components using the translate HoC receive the t function as a prop
  withTranslation: () => Component => {
    Component.defaultProps = { ...Component.defaultProps, t: () => "" };
    return Component;
  },
}));

但是当你这样做时,你没有initReactI18next在这里尝试使用:

import { initReactI18next } from "react-i18next";
i18next.use(initReactI18next).init(config);

文档破坏了你:(

您需要的是删除存根或initReactI18next在存根模块中提供密钥。

我已经在这里通知了作者:https ://github.com/i18next/react-i18next-gitbook/pull/42

于 2019-12-22T21:24:42.220 回答
0

你需要模拟initReactI18next. 尝试以下操作:

jest.mock('react-i18next', () => {
  const useMock = [k => k, {}];
  useMock.t = k => k;

  return {
    useTranslation: () => useMock,
    initReactI18next: () => {}
  };
});
于 2020-04-09T19:46:18.953 回答
0

也许你做了从 <=V9到 >=的更新V10。因为reactI18nextModule在 >= 中不再可用V10。尝试initReactI18next改用。

有关更多详细信息,请访问https://react.i18next.com/latest/migrating-v9-to-v10

于 2019-06-25T13:10:02.030 回答
-3

失败的功能:

function use(module) {
      if (module.type === 'backend') { // cannot read `type` of `undefined`

结论:moduleundefined。它来自:

i18next.use(initReactI18next)

结论:initReactI18next未定义。它来自:

import { initReactI18next } from "react-i18next";

结论:initReactI18next不是出口的东西react-i18next

于 2019-04-04T04:15:08.090 回答