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

