我有一个子组件,它根据作为道具传递的对象数组呈现按钮。这
传递给事件处理程序的值是一个如下所示的对象:{ 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()
无济于事。
答案 0 :(得分:2)
您必须在 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)
})