我有一个带按钮的Vue组件。单击按钮时,将调用一个方法。我正在使用Jest进行单元测试。我期望vue-test-utils
中的.trigger
方法在按钮上创建一个合成事件,但它什么也没做。
我尝试通过调用wrapper.vm.addService()
然后使用console.log(wrapper.emitted())
直接在包装器上调用该方法,我确实可以看到触发了一个事件。所以我的问题是为什么addServiceBtn.trigger('click')
什么都不做。
console.log(wrapper.emitted())
是一个空对象。测试结果失败,错误消息: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>
测试.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()
})
})
您的HTML代码中有一个小错误。您将@click
事件绑定到不带任何this
的方法。成功:
<v-btn flat color="green" id="addServiceBtn" @click="addService($event)">Add</v-btn>
实际上,原始代码中的测试不起作用还有另一个原因:它是函数调用中的括号。我发现语法@click="addService"
会导致测试失败,而非常相似(但不知何故不鼓励(的语法@click="addService()"
会成功。
示例:
test('Click calls the right function', () => {
// wrapper is declared before this test and initialized inside the beforeEach
wrapper.vm.testFunction = jest.fn();
const $btnDiscard = wrapper.find('.btn-discard');
$btnDiscard.trigger('click');
expect(wrapper.vm.testFunction).toHaveBeenCalled();
});
此测试失败,语法为:
<button class="btn blue-empty-btn btn-discard" @click="testFunction">
{{ sysDizVal('remove') }}
</button>
但使用了以下语法:
<button class="btn blue-empty-btn btn-discard" @click="testFunction()">
{{ sysDizVal('remove') }}
</button>
对我来说,它没有工作,但在使用vue测试utils测试时未能触发事件,直到我添加.nature
<v-btn @click.native="addToCart($event)">
Add
</v-btn>
它不起作用的原因是因为<template>
中的this.addService
建议删除this
,并说只有@click="addService($event)"
或@click="addService"
也可以正常工作,但中没有传递事件