You need to enable JavaScript to run this app. React Router v6测试页面报Cannot read properties of undefined (reading 'pathname')如何解决
优惠活动
大模型
产品
解决方案
定价
更多

React Router v6测试页面报Cannot read properties of undefined (reading 'pathname')如何解决

React Router v6 测试自定义history实现方案

问题背景

在测试带有<Link>的组件时,v5.3及之前版本通常使用以下模式获取当前location用于测试:

const renderInRouter = () => {
  const history = createMemoryHistory();
  const wrapper = render(
    <Router history={history}>
      <MyPage />
    </Router>
  );
  return { ...wrapper, history };
}

升级到v6后运行测试会抛出如下错误:

FAIL  ./demo.test.js
  ✕ works (205 ms)

  ● works

    TypeError: Cannot read properties of undefined (reading 'pathname')

      at Router (../packages/react-router/index.tsx:281:5)

      ...

v6的Router组件API已调整,不再接收history属性,新的属性定义如下:

interface RouterProps {
  basename?: string;
  children?: React.ReactNode;
  location: Partial<Location> | string;
  navigationType?: NavigationType;
  navigator: Navigator;
  static?: boolean;
}

仅传入navigator={history}仍会报错,需要调整实现方式。


解决方案

报错的核心原因是v6的Router组件要求location为必填属性,仅传入navigator不会自动关联当前history的location,需要同时传入两个属性:

修正后的自定义history封装

const renderInRouter = (initialRoute = "/") => {
  // 可指定初始路由
  const history = createMemoryHistory({
    initialEntries: [initialRoute]
  });
  const wrapper = render(
    <Router 
      navigator={history} 
      location={history.location}
    >
      <MyPage />
    </Router>
  );
  // 仍可返回history实例用于后续测试跳转、监听等操作
  return { ...wrapper, history };
}

复现用例修正版本(index.test.js)

const { render } = require("@testing-library/react");
const { createMemoryHistory } = require("history");
const React = require("react");
const { Router } = require("react-router-dom");

it("works in v6", () => {
  const history = createMemoryHistory();
  render(
    <Router 
      navigator={history}
      location={history.location}
    ></Router>
  );
});

简化方案(无需自定义history时使用)

如果不需要主动操作history实例,推荐直接使用v6内置的MemoryRouter,无需手动维护history和属性传递:

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

const renderInRouter = () => {
  return render(
    <MemoryRouter initialEntries={["/target-route"]}>
      <MyPage />
    </MemoryRouter>
  )
}

内容的提问来源于stack exchange,提问作者jonrsharpe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 04:15:01