React 和 Jest:无法从 React-router-dom 模拟 Link 功能

问题描述 投票:0回答:1

我正在尝试从react-router-dom模拟Link对象。我已经成功模拟了 hooks。

我的模拟:

jest.mock("react-router-dom", () => ({
      useLocation: jest.fn().mockReturnValue({
        pathname: "/another-route",
        search: "",
        hash: "",
        state: null,
        key: "SomeKey",
      }),
      useHistory: jest.fn().mockReturnValue({
        push: (mockString: string) => {},
      }),
      Link: jest.fn().mockReturnValue(<div></div>),
    }));

SearchButton.test.tsx 文件中的组件渲染:

 const renderSearchButton = () =>
render(
  <ReduxProvider store={store}>
    <SearchButton />
  </ReduxProvider>
);

Searchbutton.tsx 文件中的SearchButtonComponent

<Link
  to={{
    pathname,
    search: mappingPropsToSearchQuery,
  }}
>
  <button
    className={`search-button ${additionalClassName}`}
    onClick={onPressed}
  >
    Szukaj
  </button>
</Link>

我遇到的错误:

 console.error
  Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

  Check the render method of `SearchButton`.
      at SearchButton (/mnt/d/projekty/ReactJs/rezerwuj/rezerwujfrontend/src/interface/components/SearchButton/SearchButton.tsx:24:22)
      at Provider (/mnt/d/projekty/ReactJs/rezerwuj/rezerwujfrontend/node_modules/react-redux/lib/components/Provider.js:21:20)
      at ReduxProvider (/mnt/d/projekty/ReactJs/rezerwuj/rezerwujfrontend/src/stateManagment/ReduxProvider.tsx:17:23)

  26 |   const pathname = "/lista-restauracji";
  27 |   return (
> 28 |     <Link
     |     ^
  29 |       to={{
  30 |         pathname,
  31 |         search: mappingPropsToSearchQuery,

我只是想测试组件是否正确渲染。

reactjs unit-testing react-router react-router-dom ts-jest
1个回答
0
投票

我知道已经快四年了,但我会为其他阅读这篇文章的人回答。

在您的第一次模拟中,您可以简单地尝试

Link: jest.fn().mockReturnValue(<div></div>)
,而不是 
Link: jest.fn(),

© www.soinside.com 2019 - 2024. All rights reserved.