如何在Vue中测试嵌套插槽?求解正确实现语法
解决Vue测试中嵌套插槽的传递问题
你当前的写法错误在于,在字符串模板里使用slot属性是Vue 2的旧语法,且Vue Test Utils中传递嵌套插槽需要用对象形式的嵌套插槽语法,而非字符串模板嵌套<template slot="xxx">。
正确写法(Vue 2 + Vue Test Utils 1.x)
如果你的项目基于Vue 2,可通过嵌套对象传递子插槽:
it('should render drop down', async () => { const wrapper = mount(MyComponent, { slots: { utilities: { // 嵌套插槽:键为子插槽名称,值为插槽内容 'drop-down': ` <input placeholder="Search bar" class="header-bar-mobile-drop-down-utility__example"> ` } } }); expect(wrapper.find(".header-bar-mobile-drop-down-utility").exists()).to.equal(true) });
正确写法(Vue 3 + Vue Test Utils 2.x)
如果是Vue 3项目,Vue Test Utils 2.x支持更贴近Vue 3语法的嵌套插槽写法,可选择字符串模板或渲染函数:
it('should render drop down', async () => { const wrapper = mount(MyComponent, { slots: { utilities: { // 方式1:字符串模板 'drop-down': '<input placeholder="Search bar" class="header-bar-mobile-drop-down-utility__example">', // 方式2:渲染函数(类型更安全) // 'drop-down': () => h('input', { // placeholder: 'Search bar', // class: 'header-bar-mobile-drop-down-utility__example' // }) } } }); expect(wrapper.find(".header-bar-mobile-drop-down-utility").exists()).to.equal(true) });
关键注意点
- 无需在插槽内容里写
<template slot="xxx">,直接通过插槽对象的嵌套键值对传递子插槽。 - 确保
MyComponent的utilities插槽内部确实定义了drop-down子插槽(即组件内有<slot name="drop-down"></slot>嵌套在utilities插槽区域中)。
内容的提问来源于stack exchange,提问作者Sonny49
相关产品推荐
相关产品推荐

