【问题标题】:Declare children components in wrapper for jest在包装器中声明子组件以开玩笑
【发布时间】: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组件的代码吗?

标签: vue.js jestjs


【解决方案1】:

我建议你找到所有Tab 组件,而不是在测试中使用$children 属性。

describe('Tabs', () => {    
  it('should display tabs', async() => {
     const wrapper = shallowMount(Tabs, {})
     expect(wrapper.findAllComponents(Tab)).toHaveLength(YOUR_EXPECTED_LENGTH)
  })
})

我还建议你重新考虑Tabs 的组件结构:你最好在Tabs 中使用v-for 渲染每个Tab。操作每个Tab 会容易得多。

还有另一个在 Vue 中创建选项卡的好方法 - 使用 dynamic components

【讨论】:

  • console.log(wrapper.findAllComponents(Tab).length) return 0
  • Tab 组件是否已渲染?您可以致电console.log(wrapper.html())查看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
  • 2018-05-15
相关资源
最近更新 更多