Jest.js React Router V6 - useNavigate()只能在组件的上下文中使用< Router>

zfycwa2u  于 2023-06-27  发布在  Jest
关注(0)|答案(3)|浏览(159)

我已经安装了react-router-domv 6。当我使用Jest-Enzyme运行非常基本的测试时,我遇到了上述错误:

expect(shallow(<CustomerListTable customers={mockCustomers} />).length).toEqual(1);

我已经遇到了这个similar issue mentioned here,但我已经在做提供的答案。甚至尝试做import { BrowserRouter as Router } from "react-router-dom";。我错过了什么?

index.js

import React, { Suspense } from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { StrictMode } from "react";
import { BrowserRouter } from "react-router-dom";
...

ReactDOM.render(
  <StrictMode>
          ...
            <BrowserRouter>
              <AuthProvider>
                <App />
              </AuthProvider>
            </BrowserRouter>
          ...
  </StrictMode>,
  document.getElementById("root")
);

App.js

import React from "react";
import { useRoutes } from "react-router-dom";
import Routing from "./routes";
import useAuth from "./hooks/useAuth";
import { CreateCustomTheme } from "./theme";
import { ThemeProvider } from "@mui/material/styles";
import CssBaseline from "@mui/material/CssBaseline";
import useSettings from "./hooks/useSettings";
import useScrollReset from "./hooks/useScrollReset";
import SplashScreen from "./components/splashScreen/SplashScreen";

const App = () => {
  const content = useRoutes(Routing());
  const { settings } = useSettings();
  const auth = useAuth();

  useScrollReset();

  const theme = CreateCustomTheme({
    direction: settings.direction,
    responsiveFontSizes: settings.responsiveFontSizes,
    roundedCorners: settings.roundedCorners,
    theme: settings.theme,
  });
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      {auth.isInitialized ? content : <SplashScreen />}
    </ThemeProvider>
  );
};

export default App;
zaqlnxep

zaqlnxep1#

    • 要解决此问题,您可以在编写测试用例的文件的所有导入之前直接mock useNavigate(),如下所示:-**
const mockedUsedNavigate = jest.fn();
jest.mock('react-router-dom', () => ({
   ...jest.requireActual('react-router-dom'),
  useNavigate: () => mockedUsedNavigate,
}));
woobm2wo

woobm2wo2#

看起来您正在测试的CustomerListTable组件 * 在隔离 * 中无法访问它在应用程序中正常呈现时所期望的路由上下文。在使用提供程序(redux,主题/样式,本地化,***路由***等)测试组件时,需要 Package 组件是完全正常的,这些提供程序提供了组件正在访问的特定React Context值,通常通过React hooks。
对于单元测试,您应该用组件期望拥有的提供程序 Package 组件。

expect(shallow(
  <BrowserRouter>
    <CustomerListTable customers={mockCustomers} />
  </BrowserRouter>
).length).toEqual(1);

我已经很久没有使用过Enzyme了,所以我不确定shallow渲染器是否还能工作,但是如果不能,那么就换到完整的mount测试渲染器。

lnlaulya

lnlaulya3#

使用"react-router-dom": "^6.12.0",
对于单元测试,我解决了这样的问题:
1.导入内存路由器:

import { MemoryRouter as Router } from "react-router-dom";

1.用路由器包裹组件

<Router>
    <CustomerListTable customers={mockCustomers} />
</Router>

相关问题