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

vue-test-utils中shallowMount懒加载组件时未正确Stub子组件问题

解决Vue Test Utils v1.x中懒加载组件无法被shallowMount Stub的问题

我遇到过一模一样的问题!核心原因是你用异步工厂函数注册的Child组件,在Vue Test Utils v1.0.0-beta.29版本里,shallowMount没办法自动识别这类异步组件并替换成Stub——它会默认执行这个工厂函数去加载真实的子组件,所以才会渲染整个组件树。

给你几个亲测有效的解决方案:

方案1:正确配置stubs选项

你之前尝试过stubs但没生效,大概率是写法细节没注意。要保证stubs的key和父组件里注册的组件名完全一致(这里是Child,大小写敏感),试试下面两种写法:

写法A:自动生成默认Stub

const wrapper = shallowMount(ParentComponent, {
  stubs: { Child: true }, // 直接指定为true,会生成<child-stub>标签
  propsData: {
    markets: [{}, {}] // 传入测试用的markets数据
  }
})

写法B:自定义Stub模板

如果需要更定制化的Stub,可以手动写模板:

const wrapper = shallowMount(ParentComponent, {
  stubs: {
    Child: {
      name: 'Child',
      template: '<child-stub />'
    }
  },
  propsData: {
    markets: [{}, {}]
  }
})

方案2:用Jest Mock异步组件导入

如果方案1还是不行,直接在测试文件顶部mock子组件的导入,让异步加载返回Stub:

// 测试文件开头
jest.mock('./TimelineItem.vue', () => ({
  default: {
    name: 'Child',
    template: '<child-stub />'
  }
}))

// 然后正常写测试逻辑
describe('ParentComponent', () => {
  it('renders child stubs correctly', () => {
    const wrapper = shallowMount(ParentComponent, {
      propsData: { markets: [{}, {}] }
    })
    expect(wrapper.html()).toMatchSnapshot()
  })
})

方案3:临时修改组件注册(不推荐,侵入业务代码)

万不得已的情况下,可以给测试环境单独注册同步Stub组件,但这个方法会修改业务代码,尽量不用:

// 父组件的script部分
let ChildComponent
if (process.env.NODE_ENV === 'test') {
  // 测试环境下直接用Stub
  ChildComponent = { name: 'Child', template: '<child-stub />' }
} else {
  // 生产环境用懒加载
  ChildComponent = () => import('./TimelineItem.vue')
}

export default {
  components: {
    Child: ChildComponent
  },
  props: {
    markets: {
      type: Array,
      default: () => []
    }
  }
}

试完上面的方法,你的快照应该就能生成<child-stub>标签,和期望的结果一致了!

内容的提问来源于stack exchange,提问作者Xavi Sanchez Mir

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:19:24