繁体   English   中英

vue-test-util 点击触发按钮未触发

[英]vue-test-util click trigger on button not firing

我有一个带按钮的 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.

服务项.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>

测试规范.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>

它不起作用的原因是因为<template> this.addService建议您删除this并说只有@click="addService($event)"@click="addService"也可以正常工作,但是没有事件传入

对我来说它没有用,但是在使用vue-test-utils 进行测试时未能触发事件,直到我添加了.native

<v-btn @click.native="addToCart($event)">
      Add
</v-btn>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM