首页 > 解决方案 > React 测试库、动态导入和 React Router DOM 总是渲染未找到的组件

问题描述

我在测试简单导航时遇到了一些麻烦,
我有一个使用 react-router-dom 的反应应用程序,并且应用程序组件被悬念包裹着。
我还动态导入我的组件以便能够进行代码拆分。

出于某种原因,在单元测试中,当我从主页触发点击导航关于链接时。
它总是呈现 404 NotFound 组件,而不是存在的 about 组件
我做错了什么?

主.js

const Main = () => <h1>Home page</h1>;

关于.js

const About = () => <h1>About page</h1>;

NotFound.js

const NotFound = () => <div>404 this page does not exist</div>;

导航.js

const Nav = () => (
  <div className="dummy-nav">
    <ul>
      <li>
        <Link to="/">Home</Link>
      </li>
      <li>
        <Link to="/about">About</Link>
      </li>
    </ul>
  </div>
);

应用程序.js

import React, { Component, Suspense, lazy } from "react";
import { Switch, Route } from "react-router-dom";
import Nav from "./Nav";

 const Main = lazy(() => import(/* webpackChunkName: "Main" */ "./Main"));
 const About = lazy(() => import(/* webpackChunkName: "About" */ "./About"));
 const NotFound = lazy(() =>
  import(/* webpackChunkName: "About" */ "./NotFound")
 );

class App extends Component {
  render() {
    return (
      <Suspense fallback={<div>Loading...</div>}>
        <div>This is the App</div>
        <Nav />
        <Switch>
          <Route exact path="/" component={Main} />
          <Route path="/about" component={About} />
          <Route render={() => <NotFound />} />
        </Switch>
      </Suspense>
    );
  }
}

app.test.js

function renderWithRouter(
  ui,
  {
    route = "/",
    history = createMemoryHistory({ initialEntries: [route] }),
    ...renderOptions
  } = {}
) {
  // eslint-disable-next-line react/prop-types
  function Wrapper({ children }) {
    return <Router history={history}>{children}</Router>;
  }
  return {
    ...render(ui, { wrapper: Wrapper, ...renderOptions }),
    history
  };
}

test("renders homepage by default and can navigate to about", async () => {
  renderWithRouter(<App />);
  screen.getByText(/Home page/i);
  const link = screen.getByRole("link", { name: /About/i });
  userEvent.click(link);
  await waitFor(() => screen.getByText(/About page/i));
  screen.debug();
});

这是一个代码沙箱,其中包含我正在使用的损坏测试和应用程序结构,如果您有任何使用和测试惰性和动态导入的技巧,请分享

https://codesandbox.io/s/react-router-suspense-lrnp7?file=/src/App.js

标签: reactjsjestjsreact-router-domreact-testing-library

解决方案


react-router-dom v6如果你想使用,你应该使用history v5.x.

https://www.npmjs.com/package/history


推荐阅读