无需模拟就可以测试无渲染组件吗?我有这样的组件
export default {
render() {
return this.$scopedSlots.default({
loadData: this.loadData,
})
},
在模板中调用
<template>
<div>
<renderless-component v-slot="componentProps" >
<button @click="componentProps.loadData">
</renderless-component>
</div>
</template>
当尝试使用mount或shallowMount对其进行测试时,按钮未呈现。 那么,对无渲染组件进行单元测试的正确方法是什么?
答案 0 :(得分:0)
像这样自定义shallowMountView,并在需要的地方导入。不要全局导入 Renderless 组件。
global.shallowMountView = (viewComponent, options) => {
return shallowMount(viewComponent, {
...options, //TODO: use deepMerge instead
// Vue 3
global: {
stubs: {
RenderlessComponent: {
setup(props, { slots }) {
// For anyone use Fragments aka multi-root components use
// h('div', slots.default(props)) instead of
// slots.default(props)
return () => (slots.default ? slots.default(props) : '');
},
},
},
},
// Vue 2
stubs: {
RenderlessComponent: {
render(h, { slots }) {
return this.$scopedSlots.default(this.$props) || '';
},
},
},
});
};
// viewComponent.vue
import Layout from '@layouts/layout.vue';
export default {
components: {
Layout, // Renderless component (Layout.vue)
}
}
<template>
<Layout is="main" data-test="view-layout">Test</Layout>
<template/>
// Renderless component (Layout.vue)
import Layout from '@layouts/layout.vue';
export default {
setup(props) { // Vue 3
return () => slots.default(props);
},
render(h) { // Vue 2 use render
return this.$scopedSlots.default(this.$props) || '';
}
}