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
相关产品推荐
相关产品推荐

