I am facing an issue with my Vue component that contains a button triggering a method on click. I am currently using Jest for unit testing. I expected the .trigger
method from vue-test-utils
to generate a synthetic event on the button, but it seems to be ineffective.
When I directly call the method on the wrapper with wrapper.vm.addService()
and then check with console.log(wrapper.emitted())
, I can confirm that an event is indeed being triggered. So, my confusion lies in why addServiceBtn.trigger('click')
is not yielding any result.
The output of console.log(wrapper.emitted())
shows an empty object and the test fails with the error message:
Expected spy to have been called, but it was not called.
ServiceItem.vue
<template>
<v-flex xs2>
<v-card>
<v-card-text id="itemTitle">{{ item.title }}</v-card-text>
<v-card-actions>
<v-btn flat color="green" id="addServiceBtn" @click="this.addService">Add</v-btn>
</v-card-actions>
</v-card>
</v-flex>
</template>
<script>
export default {
data: () => ({
title: ''
}),
props: {
item: Object
},
methods: {
addService: function (event) {
console.log('service item')
this.$emit('add-service')
}
}
}
</script>
tests.spec.js
import { shallowMount, mount } from '@vue/test-utils'
import ServiceItem from '@/components/ServiceItem.vue'
import Vue from 'vue';
import Vuetify from 'vuetify';
Vue.use(Vuetify);
describe('ServiceItem.vue', () => {
it('emits add-service when Add button is clicked', () => {
const item = {
title: 'Service'
}
const wrapper = mount(ServiceItem, {
propsData: { item }
})
expect(wrapper.find('#addServiceBtn').exists()).toBe(true)
const addServiceBtn = wrapper.find('#addServiceBtn')
const spy = spyOn(wrapper.vm, 'addService')
console.log(wrapper.emitted())
addServiceBtn.trigger('click')
expect(wrapper.vm.addService).toBeCalled()
})
})