【问题标题】:Typescript, Jest and i18next: Can't see text in React componentTypescript、Jest 和 i18next:在 React 组件中看不到文本
【发布时间】:2017-09-17 07:58:14
【问题描述】:

我正在测试一个使用 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() 存根返回 undefined 而不是“你好,世界!”,但我不确定。

我尝试unmock("i18next") 没有任何运气。

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

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

【问题讨论】:

  • 你能否在你的文件中添加一个console.log(t("Hello, world!")),只是为了检查问题是否真的与i18next有关

标签: reactjs typescript jestjs enzyme i18next


【解决方案1】:

不知道为什么它不起作用,但您可以像这样模拟 put i18next

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

【讨论】:

  • 谢谢,这行得通。看起来我的问题与 Typescript 编译器有关。我已经更新了描述。
猜你喜欢
  • 2021-03-19
  • 2020-04-03
  • 2019-07-13
  • 2020-05-05
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 1970-01-01
  • 2018-07-15
相关资源
最近更新 更多