Typescript、Jest 和 i18next:在 React 组件中看不到文本

Typescript, Jest and i18next: Can't see text in React component

我正在测试使用 i18next 进行国际化的 React 组件。

组件:

import * as React from "react";
import { t } from "i18next";

export function Hello(_props) {
  return <div className="widget-header">
    {t("Hello, world!")}
  </div>;
}

测试:

import * as React from "react";
import { render } from "enzyme";
import { Hello } from "./hello";

describe("<Hello />", () => {
  it("says hi", () => {
    let hi = render(<Hello />);
    // FAILS!
    // Expected "" to contain "Hello"
    expect(hi.text()).toContain("Hello");
  });
})

我怀疑 Jest 将 i18next.t() 存入 return undefined 而不是 "Hello, world!",但我不确定。

我试过 unmock("i18next") 但运气不好。

如何在 Jest 中为 i18next 组件编写测试?

更新: 我使用 Typescript 作为我的编译器。似乎有一个 hoisting issue 和我用于 Typescript 的加载器(ES6 提升导入,jest.unmock 不是 - Babel 用户有一个插件来处理这个)。

不确定为什么它不起作用,但您可以像这样模拟放置 i18next

jest.mock('i18next', () => ({
  t: (i) => i
}))