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

Vue3组件默认插槽在Vue Test Utils单元测试中未渲染的问题排查

问题原因与解决方案

你遇到的核心问题是Headless UI的DisclosurePanel默认处于收起状态,此时组件不会渲染真实的面板DOM,只会输出注释节点<!---->,所以测试时看不到默认插槽的内容。

解决步骤

方法1:通过prop控制组件展开状态

如果你的封装组件暴露了控制展开/收起的prop(比如open),挂载时直接传入open: true,强制面板展开:

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

test('验证默认插槽内容', () => {
  const wrapper = mount(YourDisclosureComponent, {
    props: {
      open: true // 强制展开面板
    },
    slots: {
      default: '<div class="panel-content">这是默认插槽内容</div>'
    }
  })

  expect(wrapper.find('.panel-content').exists()).toBe(true)
  expect(wrapper.find('.panel-content').text()).toBe('这是默认插槽内容')
})

方法2:模拟点击展开按钮触发面板显示

如果组件没有暴露控制状态的prop,需要模拟用户交互,点击DisclosureButton来打开面板:

test('验证默认插槽内容', async () => {
  const wrapper = mount(YourDisclosureComponent, {
    slots: {
      default: '<p>测试内容</p>'
    }
  })

  // 找到展开按钮并触发点击(选择器需匹配你的组件结构)
  await wrapper.find('button').trigger('click')

  // 面板展开后断言插槽内容
  expect(wrapper.find('p').text()).toBe('测试内容')
})

额外注意事项

  • 多插槽测试的核心是确保对应组件区域处于正确渲染状态:title插槽能正常测试,是因为DisclosureButton始终处于渲染状态,不受展开/收起影响。
  • 若用wrapper.html()查看DOM,需在面板展开后调用,才能看到默认插槽的真实内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:42:49