You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Testing中mock router.push失败,点击按钮未触发调用求助

问题分析与解决方法

1. 核心问题:预期参数不匹配

你的组件中调用 router.push 时传入的是包含 pathname 和 query 的完整对象,但测试代码里却期望它仅接收路径字符串。这是导致断言失败的直接原因。

2. 修正步骤

调整测试断言

将断言改为匹配组件实际传入的参数结构,确保 pathname 和 query 与组件逻辑完全一致:

优化元素查找

按钮初始状态下就显示 "Proceed"(loading 默认值为 false),无需使用异步查找方法 findByRole,直接用同步的 getByRole 即可。

确保路由上下文正确

确认导入的 RouterContext 来自 next/router(若使用 Next.js),并正确将 mock 路由注入组件上下文。


修正后的测试代码

it("proceed button should redirect", () => {
  // 创建带 jest mock 的路由对象
  const router = {
    push: jest.fn(),
    query: { id: "", redirect_url: "", key: "" },
    pathname: "consent"
  };

  render(
    <RouterContext.Provider value={router}>
      <WelcomeScreen {...propData} />
    </RouterContext.Provider>
  );

  // 直接获取按钮,无需等待
  const proceedButton = screen.getByRole('button', { name: /Proceed/i });
  fireEvent.click(proceedButton);

  // 断言 push 方法被调用时传入正确的对象
  expect(router.push).toHaveBeenCalledWith({
    pathname: "../../links/[id]/config",
    query: { 
      id: propData.id, 
      redirect_url: propData.redirect_url 
    },
  });
});

额外提示(若使用 next-router-mock)

如果你使用 next-router-mock 库生成 mock 路由,确保生成的对象包含 spy 方法:

import { createMockRouter } from 'next-router-mock';

it("proceed button should redirect", () => {
  const router = createMockRouter({ 
    query: { id: "", redirect_url: "", key: "" }, 
    pathname: 'consent' 
  });

  render(
    <RouterContext.Provider value={router}>
      <WelcomeScreen {...propData} />
    </RouterContext.Provider>
  );

  const proceedButton = screen.getByRole('button', { name: /Proceed/i });
  fireEvent.click(proceedButton);

  expect(router.push).toHaveBeenCalledWith({
    pathname: "../../links/[id]/config",
    query: { id: propData.id, redirect_url: propData.redirect_url },
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 15:20:51