【发布时间】:2021-06-01 15:14:00
【问题描述】:
我有一个这样使用的组件“标签”:
<template>
<Tabs>
<Tab title="Title 1">Content test 1</Tab>
<Tab title="Title 2">Content test 2</Tab>
<Tab title="Title 3">Content test 3</Tab>
</Tabs>
</template>
我使用this.$children 来检索我的选项卡组件中的所有选项卡。
如何在我的单元测试中模拟这个以在 Tabs 组件中有子级?
我想要这个:
describe('Tabs', () => {
it('should display tabs', async() => {
const wrapper = shallowMount(Tabs, {})
console.log(wrapper.vm.$children.length) // ==> Return Tab count
expect(true).toEqual(true)
})
})
提前感谢您的帮助!
编辑 标签组件:
<template>
<section>
<ul>
<li v-for="(tab, index) in tabs" :key="tab.title" v-on:click="selectTab(index)">
<button
:class="{ 'active': index === selectedIndex }"
type="button"
>
{{ tab.title }}
</button>
</li>
</ul>
<div>
<slot></slot>
</div>
</section>
</template>
<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import Tab from './tab.vue'
@Component
export default class Tabs extends Vue {
@Prop({ required: false, type: Number, default: 0 }) private activeTab: number
private selectedIndex: number
private tabs: Tab[] = []
mounted(): void {
this.selectTab(this.activeTab)
}
created(): void {
this.tabs = this.$children as Tab[]
}
selectTab(i: number): void {
this.selectedIndex = i
// loop over all the tabs
this.tabs.forEach((tab, index) => {
tab.isActive = index === i
})
}
}
</script>
【问题讨论】:
-
你能提供你的
Tabs组件的代码吗?