简体   繁体   English

用 Jest 测试 Vue:由父组件处理的自定义事件,由子组件发出

[英]Testing Vue with Jest: custom event handled by parent, emitted by child component

I have a set of parent & child vue components.我有一组父子 vue 组件。 The child emits an event that the parent handles.孩子发出一个由父母处理的事件。 I'd like to test that it handles the custom event correctly, but I am stuck.我想测试它是否正确处理自定义事件,但我被卡住了。

Parent.vue父.vue

<template>
  <div id="app" class="container">
    <!-- phonebook -->
    <ChildComponent
      class="row mt-4"
      @customEvent="val => customEventHandler(val)"
    ></ChildComponent>
  </div>
</template>

<script>
  import ChildComponent from './components/ChildComponent.vue'

  export default {
    name: 'App',
    components: {
      ChildComponent,
    },
    data() {
      return {
        test: [1, 2, 3, 4]
      };
    },
    methods: {
      customEventHandler(id) {
        // removes item `id` from the `test` array
        this.test = this.test.filter((item) => item !== id);
      },
    }
  };
</script>

This is one thing I've tried:这是我尝试过的一件事:

Parent.spec.js父规范.js

import { mount, shallowMount } from "@vue/test-utils";
import  Parent from '../../src/Parent.vue';
import  ChildComponent from '../../src/components/ChildComponent.vue';

describe('customEvent event', () => {
  beforeEach(() => {
    parent = mount(Parent, {
      data() {
        return {
          test: [1, 2, 3, 4]
        };
      },
    });
  });

  it('should trigger the customEventHandler method', async() => {
    const spy = jest.spyOn(parent.vm, 'customEventHandler');
    await parent.findComponent(ChildComponent).trigger('customEvent', 2);

    expect(spy).toHaveBeenCalled();
  })
})

The test above fails and I'm not sure why.上面的测试失败了,我不知道为什么。

I've also tried the following tests:我还尝试了以下测试:

// check what the spy has been called with 
expect(spy).toHaveBeenCalledWith(2);

// test the side-effects of the `customEventHandler` method
expect(parent.vm.test.length).toEqual(3)

These also fail - it's as though the event isn't being triggered at all (is that it?), or I'm trying to test something that isn't possible.这些也失败了——就好像事件根本没有被触发(是这样吗?),或者我正在尝试测试一些不可能的东西。

Is there an accepted way to test a parent component's handling of an event emitted by a child component?是否有一种公认的方法来测试父组件对子组件发出的事件的处理?

Triggering events触发事件

trigger() only works for native DOM events. trigger()仅适用于原生 DOM 事件。 For custom events, use wrapper.vm.$emit() (and no need to await it):对于自定义事件,使用wrapper.vm.$emit() (无需await它):

// await parent.findComponent(ChildComponent).trigger('customEvent', 2);
//                                            ^^^^^^^ ❌

parent.findComponent(ChildComponent).vm.$emit('customEvent', 2);

Spying on methods监视方法

Vue 2 does not support spying on methods from the wrapper.vm instance, so the spying needs to be done on the component definition ( Parent.methods ) before mounting : Vue 2 不支持对wrapper.vm实例中的方法进行监视,因此需要在挂载之前组件定义Parent.methods )进行监视:

// const spy = jest.spyOn(parent.vm, 'customEventHandler');
//                        ^^^^^^^^^ ❌ not supported in Vue 2

const spy = jest.spyOn(Parent.methods, 'customEventHandler')
const parent = mount(Parent)

demo 演示

Note that Vue 3 does support spying via wrapper.vm .请注意,Vue 3确实支持通过wrapper.vm进行间谍活动。

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

相关问题 Vue 父组件无法捕获子组件发出的事件 - Vue parent component unable to catch event emitted from the child 如何处理自定义子事件,该事件通过this。$ emit在父组件中<script> portion of the .vue file? - How can I handle a custom child event, emitted via this.$emit, in a parent component, within the <script> portion of the .vue file? 当在子组件中发出事件时,父组件中未接收到对象 - Object is not receiving in parent component when event is emitted in child component Vue.js 中的子组件未向父组件发出数据 - Data not emitted from child to parent component in Vue.js Vue.js子组件和父组件之间未发出事件 - Vue.js no event emitted between child and parent components 发出的事件不会调用 Vue JS 组件中的父方法 - Emitted event doesn't call parent method in Vue JS component $ emit从子级到父级Vue 2的事件 - $emit an event from child to parent component Vue 2 Vue 3:从父组件向子组件发出事件 - Vue 3: Emit event from parent to child component 在 Jest (Vue) 中测试子组件时如何模拟发射 - how to mock an emit when testing a child component in Jest (Vue) 是否可以通过 Jest 测试在父级中的自定义子组件上触发 (ngModelChange) 事件? - Is it possible to trigger (ngModelChange) event on a custom child component in a parent via Jest test?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM