如何在vue 2中测试组件根元素上的事件?

时间:2019-02-20 15:57:49

标签: unit-testing vue.js vuejs2 vue-test-utils

我正在为以下组件编写单元测试:

<template>
  <sub-component
     @foo="bar"
  />
</template>
<script>
import SubComponent from './SubComponent';

export default {
  name: 'MyComponent',
  components: { SubComponent },
  methods: {
    bar(payload) {
       this.$emit('baz', ...payload);
    }
  }
}
</script>

测试将是:

import { shallowMount } from '@vue/test-utils';
import _ from 'lodash';
import MyComponent from '../../components/MyComponent';

describe('MyComponent.vue', () => {
  let wrapper;

  beforeEach(() => {
    wrapper = shallowMount(MyComponent);
  });

  it('should emit baz on subcomponent foo', () => {
    const subComp = wrapper.find('sub-component-stub');
    expect(subComp.exists()).toBe(true);          // passes

    subComp.vm.$emit('foo');

    return wrapper.vm.$nextTick().then(() => {
      expect(wrapper.emitted().baz).toBeTruthy(); // does not pass;

      // upon logging: 
      console.log(_.isEqual(wrapper, subComp));   // => true 
    })
  })
})

该示例过于简化,但是这里的原理是我想要一个可重用的<sub-component>(一个模式)和围绕它的各种功能包装(与模式类型执行的一项特定任务有关),以映射其他功能。我不需要父组件中的功能,因为它会违反DRY-我必须将其放在包含特定类型的模态的每个组件中。

如果<sub-component>不是<template>的直接子代,则可以正常工作。以某种方式,看来wrappersubComp托管在同一元素上。

应如何正确测试?

1 个答案:

答案 0 :(得分:1)

另一种可能性是在dom中找到您的元素并检查根组件发出的值。

import { shallowMount } from '@vue/test-utils'
import MyComponent from './MyComponent.vue'
import SubComponent from './SubComponent.vue'

describe('MyComponent', () => {    

  it('should emit baz on subcomponent foo', () => {
    const wrapper = shallowMount(MyComponent)
    const subComponent = wrapper.find(SubComponent)

    expect(subComponent.exists()).toBe(true)
    expect(wrapper.emitted('baz')).toBeUndefined()

    subComponent.vm.$emit('foo', ['hello'])
    expect(wrapper.emitted('baz')[0]).toEqual(['hello'])
    // or expect(wrapper).toEmit('baz', 'hello') cf. below for toEmit
  })

})

如果要为Jest自定义匹配器:

toEmit(received, eventName, data) {
  if (data) {
    expect(received.emitted()[eventName][0]).toEqual([data])
  } else {
    expect(received.emitted()[eventName][0]).toEqual([])
  }
  return { pass: true }
}