如何在 Vue 中测试组件是否发出事件?

Far*_*ntı 7 javascript mocha.js chai vue.js vue-test-utils

我有两个组件。子组件在值更改时发出“输入”事件,并且父组件通过 v-model 获取该值。我正在测试 ChildComponent。我需要使用 Vue-test-utils 编写一个测试来验证它是否有效。

父组件.vue:

<template>
 <div>
  <child-component v-model="search"></child-component>
  <other-component></other-component>
  ...
 </div>
</template>
Run Code Online (Sandbox Code Playgroud)

子组件.vue:

<template>
  <input :value="value" @change="notifyChange($event.target.value)"></input>
</template>

<script lang="ts">
  import { Component, Prop, Vue } from 'vue-property-decorator'

  @Component
  export default class ChildComponent extends Vue {

    @Prop({ default: '' }) readonly value!: string

    notifyChange(value: string) {
      this.$emit('input', value)
    }

  }
</script>
Run Code Online (Sandbox Code Playgroud)

子组件.spec.ts:

describe('ChildComponent', () => {
   let wrapper: any
   before(() => {
   wrapper = VueTestUtils.shallowMount(ChildComponent, {})
  })

   it(`Should emit 'input' event when value change`, () => {
    const rootWrapper = VueTestUtils.shallowMount(ParentComponent)
    wrapper.vm.value = 'Value'
    wrapper.findAll('input').at(0).trigger('change')
    assert.isTrue(!!rootWrapper.vm.search)
  })
})
Run Code Online (Sandbox Code Playgroud)

我没有写完全相同的代码,但逻辑是这样的。我的组件工作正常。“child-component.spec.ts”不起作用。我需要为它编写一个测试。

Non*_*404 5

已测试。如果有人正在寻找这个,这是一种测试发射的简单方法。在你的测试描述中写下这个。

describe('Close Button method', () => {
  it('emits return false if button is clicked', (done) => {
    wrapper.find('button').trigger('click')
    wrapper.vm.$nextTick(() => {
      wrapper.vm.closeModal() //closeModal is my method
      expect(wrapper.emitted().input[0]).toEqual([false]) //test if it changes
      done()
    })
  })
})
Run Code Online (Sandbox Code Playgroud)

我的 vue 组件

<div v-if="closeButton == true">
      <button
        @click="closeModal()"
      >
      ...
      </button>
</div>
Run Code Online (Sandbox Code Playgroud)

我在 vue comp 中的 props

 props: {
    value: {
      type: Boolean,
      default: false
    },
Run Code Online (Sandbox Code Playgroud)

我在 vue comp 中的方法

methods: {
    closeModal() {
      this.$emit('input', !this.value)
    }
  }
Run Code Online (Sandbox Code Playgroud)