测试值是否传递给发出事件的方法,Vue

Testing that a value is passed to a method that emits an event, Vue

我有一个子组件,它根据作为道具传递的对象数组呈现按钮。这 传递给事件处理程序的值是一个如下所示的对象:{ boxes: 1, cookieQty: 4, id: 'chocChip-4', price: 12 }.

<ul class="list-items">
      <li v-for="(item, index) in items" :key="item.id">
        <label :for="item.id" class="label-btn-cookie">{{ title }}</label>
        <button
          :id="item.cookieid"
          v-bind="$attrs"
          type="button"
          :value="item.cookieQty"
          class="cookie-buttons -shadow"
          @click="updateSelection(item)"
        >
          ...
          ...
        </button>

          methods: {
            updateSelection(value) {
              this.$emit("click", value);
             }
           }

在 Parent 组件中,Child 看起来像这样 'selectboxSize' 获取 $event 然后调度一个动作。

          <CookieSelect
            :items="chocChipBoxSizesArray"
            :title="chocChip"
            data-cookie="chocolateChip"
            @click="selectBoxSize($event)"
          />

          ....

         selectBoxSize({ cookieQty }) {
          // map the element to an object and use that key to update state
          console.log(event);
          let element = event.currentTarget.getAttribute("data-cookie");
          this.updateBoxSize({ element, cookieQty });

目前我有一个通过的测试,验证按钮点击会发出一个事件。 我想做的是测试 'updateSelection' 实际上是用传递的值调用的。

   const mockData = {
     items: chocChipBoxSizesArray,
     title: "ChocolateChip"
   };

   describe("CookieSelect", () => {
     const wrapper = shallowMount(CookieSelect, {
      localVue,
      propsData: { ...mockData }
     });
      it("emits click when clicked", () => {
       const value = { boxes: 1, cookieQty: 4, id: "chocChip-4", price: 12 };
       wrapper.find("button").trigger("click");
       expect(wrapper.emitted("click")).toHaveLength(1); // passes
       expect(wrapper.emitted("click")).toHaveBeenCalledWith(value); // error
     });
...

这是我得到的错误:

expect(received).toHaveBeenCalledWith(...expected)

    Matcher error: received value must be a mock or spy function

    Received has type:  array
    Received has value: [[{"boxes": 1, "cookieQty": 4, "id": "chocChip-4", "price": 12}]]

我试过间谍和模拟一个新的 MouseEvent() 无济于事。

您必须在 updateSelection 上设置一个间谍才能验证其调用,而 wrapper.emitted() 不会为您这样做。

使用jest.spyOn() 在安装前创建一个对导入的组件定义的监视。还要确保等待 click 触发器以确保点击的任何副作用都已解决:

import CookieSelect from '@/components/CookieSelect.vue'

it('emits click when called', async () => {
  const updateSelection = jest.spyOn(CookieSelect.methods, 'updateSelection')
  const wrapper = shallowMount(CookieSelect)
  await wrapper.find('button').trigger('click')

  const value = /*...*/
  expect(updateSelection).toHaveBeenCalledWith(value)
})