首页 > 解决方案 > 使用 v-for 指令测试渲染许多子组件的 vue 组件

问题描述

这是我的名为Musics.vue的组件:

<template>
  <div class="flex flex-wrap mb-20 md:mb-32">
    <div
      v-for="(music, index) in musics"
      :key="index"
      class="w-full sm:w-6/12 lg:w-3/12 p-3"
    >
      <MusicCard :music="music" @play="setCurrent($event)" />
    </div>
  </div>
</template>

如您所见, MusicCard在循环中。并且每个MusicCard都会向父组件发出播放事件。我可以为它写测试吗?(我尝试使用 forEach 但失败了)

这是我的测试:

  it("commits a mutation when 'MusicCard' component emits play event", () => {
    const components = wrapper.findAllComponents({ name: "MusicCard" });
    expect(components.exists()).toBe(true);
    
  });

谢谢你的帮助。

标签: javascriptunit-testingvue.jstestingvue-test-utils

解决方案


您可能需要在几个简单的测试中分解您的测试。

假设您使用导入的突变或模拟突变安装组件,您应该能够执行以下操作:

// import { mutations } from "@/store/MyAppStore.js"
// or:
const mutations = {
  myMutation: jest.fn()
}

const store = new Vuex.Store({ mutations })

const wrapper = mount(Musics, {
  store, localVue
})

describe("When Musics component is mounted, it:", () => {

  it("lists several music cards", () => 
  {
    const components = wrapper.findAllComponents({ name: "MusicCard" });
    expect(components.length).toBeGreaterThan(1);   
  })

  it("receive a play event from the 'MusicCard' components", () => 
  {   
    // assert event has been emitted
    expect(wrapper.emitted().myPlayEvent).toBeTruthy()

    // assert event count
    expect(wrapper.emitted().myPlayEvent.length).toBe(2)

    // assert event payload
    expect(wrapper.emitted().myPlayEvent[1]).toEqual([123])
  })

  it("commits a mutation when 'MusicCard' component emits play event", async () => 
  {
    wrapper.vm.$emit('myPlayEvent' /*, payload */)
    
    await wrapper.vm.$nextTick()    

    expect(mutations.myMutation).toHaveBeenCalled()

    // assert payload
    expect(mutations.myMutation).toHaveBeenCalledWith(payload)
  })

})

推荐阅读