【问题标题】:How to reuse jest mock of react-router's useHistory如何重用 react-router 的 useHistory 的 jest mock
【发布时间】:2025-12-26 15:55:16
【问题描述】:

我在我的测试中像这样嘲笑react-router-domuseHistory

jest.mock("react-router-dom", () => ({
  useHistory: () => ({
    length: 13,
    push: jest.fn(),
    block: jest.fn(),
    createHref: jest.fn(),
    go: jest.fn(),
    goBack: jest.fn(),
    goForward: jest.fn(),
    liten: jest.fn(),
    replace: jest.fn(),
    action: "REPLACE",
    location: null
  })
}));

这在单个测试中工作得非常好,但我基本上每次测试都需要它,我不想每次都复制它。

如何重复使用这个模拟?我已经尝试了显而易见的方法,将其移动到不同的文件并导出创建模拟的函数:

export default () => jest.mock("react-router-dom", () => ({...})

但是,导入它并调用函数来创建模拟会导致错误。

import useHistoryMock from "../../../testUtils/hooks/useHistory";
useHistoryMock()

然后我的组件实现抛出TypeError: Cannot read property 'history' of undefined,如果我在测试文件本身中定义模拟,它不会抛出。

重用模拟的便捷方法是什么?我正在使用打字稿,所以最好我不想破坏任何编译器规则。

【问题讨论】:

    标签: reactjs typescript react-router jestjs


    【解决方案1】:

    您可以尝试使用__mocks__ 文件夹 https://jestjs.io/docs/en/manual-mocks.html

    【讨论】: