【问题标题】:How to mock a complex react component with props using Jest/ react testing library如何使用 Jest/react 测试库模拟带有道具的复杂反应组件
【发布时间】:2020-02-07 16:48:01
【问题描述】:
import {ActualComponent} from "mycomponentlibrary";

//Below is my Mock component which I want to use as mock.
const MockComponent = props => {
    const selectedUser = {
        name: "User1",
    };
    return (
        <div>
            <div>{props.dialogTitle}</div>
            <button onClick={() => props.onSelect(selectedUser)}>{"Select"}</button>
        </div>
    );
};

//below is how am trying to mock
    jest.doMock("mycomponentlibrary", () => () => {
        return {
            __esModule: true,
            ActualComponent: jest.fn(() => MockComponent),
        };
    });

但是我看到我的测试失败了,并且在日志中我看到正在使用实际组件而不是模拟。

有什么地方做错了吗?

注意:ActualComponent 不是默认导出,我不想模拟来自 "mycomponentlibrary" 的其他组件

【问题讨论】:

  • 你需要复制箭头功能吗?
  • 阅读一些我需要使用重复箭头功能的地方,但它适用于单箭头和双箭头功能。
  • The docs 与您使用的模式不同。你想测试什么?

标签: javascript reactjs jestjs react-testing-library


【解决方案1】:
jest.mock("mycomponentlibrary", () => {
    return {
        __esModule: true,
        ActualComponent: () => MockComponent
    };
};

在这种情况下,使用 mock 代替 doMock 就足够了。

另外,除非你想监视它,否则不要使用 jest.fn() 来包装你的模拟组件。

【讨论】:

    猜你喜欢
    • 2018-02-13
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 2017-11-08
    相关资源
    最近更新 更多