如何测试需要对子事件进行响应的Vue组件?

时间:2018-08-21 15:41:31

标签: vuejs2 jestjs

我很难确定如何测试需要对子事件进行响应的单个文件Vue组件。

我有一个Gallery组件,该组件具有任意数量的Card组件作为子组件,并且必须跟踪所选的Card。单击卡片后,它会发出一个自定义事件(单击卡片),图库会通过调用select()函数来监听并作出反应。根据是否按下Shift或Meta键,Select()具有一些逻辑。我在下面创建了这些组件的简化版本:

图库组件

$data = 'HTTP/1.1 200 OK Server: Apache-Coyote/1.1 access-token: a3581f021476e4fb406c6b7c79e4095cece5d0c6 token-expiration-hours: 24 Content-Type: application/json Content-Length: 0 Date: Tue, 21 Aug 2018 14:12:27 GMT';

$explodedData = explode("access-token: ", $data);
$explodedData2 = explode(" token-expiration-hours:", $explodedData[1]);

echo $explodedData2[0]; //contains access token.

卡组件

<template>
  <div class="gallery">
    <card v-for="(item, index) in items"
      :id="item.id"
      :key="item.id"
      class="galleryCard"
      @card-click="select(item.id, $event)">
      <h2>{{ item.title }}</h2>
    </card>
  </div>
</template>

<script>
export default {
  name: "Gallery",
  props: {
    items: {
      required: true,
      type: Array,
    },
  },
  methods: {
    select: function(id, event) {
      if(event.metaKey) {
        console.log('meta + click')
      } else {
        if (event.shiftKey) {
          console.log('shift + click')
        } else {
          console.log('click')
        }
      }
    },
  },
}
</script>

我使用Jest,尝试测试Gallery组件的<template> <article :id="id" @click="handleSelect($event)" class="card"> <slot/> </article> </template> <script> export default { name: "Card", props: { id: { type: String, default: "", }, }, methods: { handleSelect: function(event) { this.$emit("card-click", event) }, }, } </script> 功能,即mockingselect()),以确保单击时选择了正确的Cards。当我触发对两张卡片的点击时,我期望在selectStub数组中看到一些东西,但是什么也没有。我还尝试发出事件,如何捕获孩子在测试中发出的事件?

图库测试

selectStub.mock.calls

selectStub.mock的所有属性(调用,实例和时间戳)均为空。我也尝试发出import { createLocalVue, mount } from "@vue/test-utils" import Gallery from "@/Gallery.vue" import Card from "@/Card.vue" const localVue = createLocalVue() let wrapper let items = [ { id: "1", title: "First" }, { id: "2", title: "Second" }, { id: "3", title: "Third" }, ] describe("Gallery.vue", () => { beforeEach(() => { wrapper = mount(Gallery, { localVue, propsData: { items: items, }, stubs: ["card"], }) }) const selectStub = jest.fn(); it("selects the correct items", () => { wrapper.setMethods({ select: selectStub }) const card1 = wrapper.findAll(".galleryCard").at(0) const card2 = wrapper.findAll(".galleryCard").at(1) card1.trigger('click') card2.trigger('click', { shiftKey: true }) console.log(selectStub.mock) }) }) 事件via vue-test-utils card-click函数,但它不会触发选择。

我如何测试Gallery wrapper.vm.$emit()方法以确保其正确响应来自儿童的事件?

0 个答案:

没有答案