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

Vue Utils测试插槽中子组件:dense属性传递与渲染异常问题

Vue Utils测试插槽子组件问题解决

问题背景

使用Vue Utils测试ComponentA与插槽内的ComponentB:

  • ComponentA包含空插槽,用于放置ComponentB
  • 需求:当ComponentA的dense属性为true时,需同步传递给插槽内的ComponentB
  • 测试异常:
    1. 控制台无法输出ComponentB的渲染内容,仅显示ComponentA容器与插槽注释
    2. 持续收到Prop类型错误警告:

      Invalid prop: type check failed for prop "value". Expected String, got Boolean with value false.
      at <ComponentB dense=undefined value=undefined ... >
      at

  • 组件实际使用示例:
<componenta>
    <componentb/>
</componenta>
  • 当前测试代码未生效,控制台输出:
<div class="ComponentA" >
  <!-- @slot Use this slot for the component. -->
</div>

问题原因

  1. 测试代码仅Stub了ComponentB,但未将其实际插入ComponentA的插槽,导致插槽为空
  2. value prop警告:Vue会自动将父组件的attrs传递给子组件,若Stub的ComponentB未声明value prop,会意外接收布尔值false触发类型校验错误

修复方案

1. 手动往插槽传入ComponentB

挂载ComponentA时,通过slots选项明确将ComponentB插入默认插槽,而不是仅依赖Stub。

2. 完善Stub避免Prop警告

在ComponentB的Stub中显式声明需要接收的props,防止Vue自动传递未知attrs导致类型错误。

3. 验证Prop传递逻辑

添加断言验证ComponentB是否正确接收dense属性。

完整测试代码

import { mount } from '@vue/test-utils'
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'

const mountTestComponent = (dense?: boolean) => {
  return mount(ComponentA, {
    props: { dense },
    // 往默认插槽插入ComponentB
    slots: {
      default: '<componentb />'
    },
    global: {
      stubs: {
        ComponentB: {
          template: '<span />',
          // 显式声明props,避免未知attrs传递导致警告
          props: ['dense', 'value']
        }
      }
    }
  })
}

describe('ComponentA.vue', () => {
  let wrapper: ReturnType<typeof mountTestComponent>

  beforeEach(() => {
    wrapper = mountTestComponent()
  })

  it('同步dense属性到插槽内的ComponentB', async () => {
    wrapper = mountTestComponent(true)
    console.log(wrapper.html()) // 现在可看到ComponentB的渲染内容
    
    // 验证ComponentB是否接收到dense=true
    const componentB = wrapper.findComponent({ name: 'ComponentB' })
    expect(componentB.props('dense')).toBe(true)
  })
})

额外说明

  • 若ComponentA使用作用域插槽传递dense,需修改插槽内容为:
    <componentb :dense="dense" />
    
    对应ComponentA的插槽定义应为:<slot :dense="dense" />
  • 若需测试ComponentB的真实交互逻辑,可移除Stub,直接挂载真实的ComponentB组件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:22:51