使用 Jest 测试 i18next 时如何修复“TypeError:无法读取未定义的属性“类型”

Jes*_*sus 4 typescript i18next jestjs react-i18next

我有一个 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;
Run Code Online (Sandbox Code Playgroud)

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

import i18n from "./i18n";

describe("i18n", () => {

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

Run Code Online (Sandbox Code Playgroud)

我希望这个测试通过,但我收到以下错误:

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

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

    value: function use(module) {
      if (module.type === 'backend') {
        this.modules.backend = module;
      }
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

小智 6

尝试这个:

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

代替

import { initReactI18next } from "react-i18next";

在此处阅读更多有关 require 与 import 以进行玩笑测试的信息:

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

希望能帮助到你 :)


bas*_*rat -3

失败的功能:

function use(module) {
      if (module.type === 'backend') { // cannot read `type` of `undefined`
Run Code Online (Sandbox Code Playgroud)

结论:moduleundefined。它来自:

i18next.use(initReactI18next)
Run Code Online (Sandbox Code Playgroud)

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

import { initReactI18next } from "react-i18next";
Run Code Online (Sandbox Code Playgroud)

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

  • `initReactI18next` 是从“react-i18next”导出的 (3认同)