I have a Child component that renders buttons based on an array of objects passed as a prop. The
value passed to the event handler is an object that looks like this: { 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);
}
}
In the Parent component, the Child looks like this and 'selectboxSize' takes the $event and then dispatches an action.
<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 });
Currently I have a passing test that verifies the button click emits an event. What I want to do is to test that 'updateSelection' is in fact called with the value passed.
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
});
...
This is the error I get:
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}]]
I've tried spies and mocking a new MouseEvent()
to no avail.
You'd have to setup a spy on updateSelection
in order to verify its calls, and wrapper.emitted()
doesn't do that for you.
Use jest.spyOn()
to create a spy on the imported component definition before mounting. Also make sure to await the click
trigger to ensure any side effects from the click have resolved:
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)
})