我已经安装了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;
3条答案
按热度按时间zaqlnxep1#
woobm2wo2#
看起来您正在测试的
CustomerListTable
组件 * 在隔离 * 中无法访问它在应用程序中正常呈现时所期望的路由上下文。在使用提供程序(redux,主题/样式,本地化,***路由***等)测试组件时,需要 Package 组件是完全正常的,这些提供程序提供了组件正在访问的特定React Context值,通常通过React hooks。对于单元测试,您应该用组件期望拥有的提供程序 Package 组件。
我已经很久没有使用过Enzyme了,所以我不确定
shallow
渲染器是否还能工作,但是如果不能,那么就换到完整的mount
测试渲染器。lnlaulya3#
使用
"react-router-dom": "^6.12.0",
对于单元测试,我解决了这样的问题:
1.导入内存路由器:
1.用路由器包裹组件