在Jest中使用useNavigate时出现Request is not defined错误求助
React Router Memory Router测试中Request未定义错误的解决办法
问题描述
测试页面跳转逻辑时,已按要求创建Memory Router,但执行navigate操作时测试崩溃,抛出如下错误:
return new Request(url, init); ^ ReferenceError: Request is not defined
使用环境:Jest 29.4.3、Vite 4.1、react-router-dom 6.8.1。曾尝试Vitest相关解决方案,但因Jest使用Babel转译,无法在当前Vite环境适配。
示例测试代码:
function Example() { const navigate = useNavigate(); function onClick() { navigate("/libraries/libraryId"); } return <button onClick={onClick} data-testid="library-entry-libraryId" />; } const routes = [ { path: "/libraries", element: <Example /> }, { path: "/libraries/:libraryId" }, ]; describe("LibraryEntry", () => { it("navigates to library", () => { const router = createMemoryRouter(routes, { initialEntries: ["/libraries"], }); render(<RouterProvider router={router} />); const entry = screen.getByTestId(`library-entry-libraryId`); fireEvent.click(entry); }); });
可行解决方案
1. 添加Web API Polyfill
React Router 6.8+版本的Memory Router依赖浏览器的Request/Response API,而Jest默认不提供这些。通过安装whatwg-fetch来补全这些API:
- 安装依赖:
npm install whatwg-fetch --save-dev
- 在Jest配置文件(
jest.config.js)中配置全局引入:
module.exports = { // 其他已有配置 setupFiles: ['whatwg-fetch'], };
如果不想全局配置,也可以在单个测试文件顶部直接引入:
import 'whatwg-fetch';
2. 手动模拟Request对象
若不想新增依赖,可在测试文件或Jest全局setup脚本中手动模拟Request类:
global.Request = class Request { constructor(url, init = {}) { this.url = url; this.method = init.method || 'GET'; // 根据需要补充其他属性/方法 } };
此方法适合简单测试场景,复杂场景建议使用完整polyfill。
3. 临时降级React Router版本
如果上述方案无法快速落地,可临时将react-router-dom降级到6.7.x版本,该版本的Memory Router未使用Request API,可直接避免此错误。
内容的提问来源于stack exchange,提问作者Ronny Efronny
相关产品推荐
相关产品推荐

