I have a Vue component with a button. On a button click, a method is called. I am using Jest for unit test. I expected .trigger
method from vue-test-utils
to create a synthetic event on the button, but it does nothing.
I tried calling the method directly on the wrapper by calling wrapper.vm.addService()
and then using console.log(wrapper.emitted())
, I indeed can see an event has been triggered. So my question is why the addServiceBtn.trigger('click')
does not do anything.
The console.log(wrapper.emitted())
is an empty object. The test result is failed with 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()
})
})
You got a little mistake in your HTML code. Your bind the @click
event to your method without any this
. make it:
<v-btn flat color="green" id="addServiceBtn" @click="addService($event)">Add</v-btn>