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

Vue3 Script Setup中router-link插槽解构isActive报错排查

解决Vue3 router-link单元测试解构slot props报错问题

问题原因

你在模板里使用了router-link的custom属性和v-slot,依赖isActive、navigate这些slot props完成渲染,但Vue Test Utils默认的router-link stub不会提供这些slot props,导致解构时拿到undefined,从而抛出TypeError: Cannot destructure property 'isActive' of 'undefined' as it is undefined错误。

解决方案

自定义router-link stub,模拟传递模板需要的slot props:

it('match snapshot', () => {
  const wrapper = shallowMount(MYView, {
    stubs: {
      'router-link': {
        props: ['to', 'custom'],
        setup(props, { slots }) {
          // 模拟slot所需的props,isActive可根据测试场景设为true/false
          return () => slots.default?.({
            isActive: false,
            navigate: () => {} // 空函数模拟导航方法
          })
        }
      }
    },
  });
  expect(wrapper.html()).toMatchSnapshot();
});

说明

  • 自定义stub通过setup函数获取slot,主动传递模板需要的isActive和navigate属性
  • isActive可以根据测试需求设置为true或false,用来模拟路由激活状态
  • navigate设为空函数即可,单元测试不需要实际触发路由跳转

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:40:54