javascript - 使用 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);
});
谢谢你的帮助。
解决方案
您可能需要在几个简单的测试中分解您的测试。
假设您使用导入的突变或模拟突变安装组件,您应该能够执行以下操作:
// 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)
})
})
推荐阅读
- java - 错误:您的 buildpack 不包含 heroku/jvm buildpack!将 heroku/jvm 添加到您的 buildpack
- http-headers - In HTTP headers with parameters, are parameter names case-sensitive?
- python - Custom activation with parameter
- ruby-on-rails - Rails 5:多对多关系和控制器
- swift - Xcode 10: Code Signing my App+Framework fails, because of failure signing 3rd party dependency framework (PromiseKit). Works in Xcode 9
- rust - 将期货链接到期权期货
- matlab - 不使用 for 循环的 2 个向量的参数
- python - 从shell调用python脚本时不执行
- c - 静态分配的数组和变量之间的内存间隙
- linux - 如何调试 localhost - 无法访问此站点