如何在Vue Test Utils中给插槽传入带必填Props的SFC?
解决插槽组件必填Props传递问题
在测试中给插槽传入带必填Props的SFC,有两种实用方法:
方法一:使用Vue渲染函数(h函数)
通过h函数可以明确指定组件及其所需Props,这是最稳妥的通用方式:
import { h } from 'vue'; import List from '../List.vue'; import ListItem from '../components/ListItem.vue'; const factoryMount = () => mount(List, { slots: { default: () => h(ListItem, { label: '测试项标签' }) }, });
h函数的第二个参数就是组件的Props对象,直接传入必填的label即可消除警告。
方法二:使用模板字符串(需注册组件)
如果更习惯模板写法,可以直接在插槽中写模板字符串,但要记得全局注册插槽组件:
import List from '../List.vue'; import ListItem from '../components/ListItem.vue'; const factoryMount = () => mount(List, { slots: { default: `<ListItem label="测试项标签" />` }, global: { components: { ListItem } } });
原写法报错原因
直接将组件传入插槽时,Vue Test Utils只会实例化组件但不会传递任何Props,自然触发必填Props的警告。上述两种方法都能在组件实例化时直接传入所需Props,从根源解决问题。
内容的提问来源于stack exchange,提问作者gemmalouise
相关产品推荐
相关产品推荐

