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

NextJS使用Jest测试时router.pathname调用startsWith报错如何解决?

问题原因

你在测试代码中对useRouter的mock返回值只包含了route属性,没有包含NavBar组件中用到的pathname属性,因此router.pathname为undefined,调用startsWith方法时触发了该类型错误。

解决方法
  • 补全useRouter的mock返回值,增加pathname等组件运行需要的属性,修改测试代码中的mock实现如下:
nextRouter.useRouter.mockImplementation(() => ({ 
  route: '/',
  pathname: '/', // 可根据测试场景赋值不同路径,比如/settings/locations测试导航激活态
  asPath: '/',
  query: {},
  push: jest.fn(),
  replace: jest.fn(),
  prefetch: jest.fn()
}));
  • 如果需要测试不同路径下的导航激活态,可在单个测试用例中使用mockImplementationOnce覆盖全局mock的返回值,示例如下:
it('高亮显示当前激活的导航项', () => {
  nextRouter.useRouter.mockImplementationOnce(() => ({
    pathname: '/settings/locations',
    route: '/settings/locations',
    asPath: '/settings/locations',
    query: {},
    push: jest.fn()
  }))
  render(<Home />)
  expect(screen.getByText('Locations').parentElement).toHaveClass('active-link')
})
  • 补充说明:如果你的组件中还用到了路由跳转、query参数等路由能力,也需要在mock返回值中对应补充push/replace/query等属性,避免出现其他属性未定义的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 08:54:06