【问题标题】:Testing Vue with Jest: custom event handled by parent, emitted by child component用 Jest 测试 Vue:由父组件处理的自定义事件,由子组件发出
【发布时间】:2021-05-05 21:21:29
【问题描述】:

我有一组父子 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>

这是我尝试过的一件事:

Parent.spec.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();
  })
})

上面的测试失败了,我不知道为什么。

我还尝试了以下测试:

// 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)

这些也失败了 - 好像事件根本没有被触发(是这样吗?),或者我正在尝试测试一些不可能的东西。

是否有一种公认的方法来测试父组件对子组件发出的事件的处理?

【问题讨论】:

    标签: javascript unit-testing vue.js jestjs vue-test-utils


    【解决方案1】:

    触发事件

    trigger() 仅适用于原生 DOM 事件。对于自定义事件,使用wrapper.vm.$emit()(不需要await):

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

    监视方法

    spy 是在vm 上设置的,但需要在安装前在组件定义 (Parent.methods) 上完成:

    // const spy = jest.spyOn(parent.vm, 'customEventHandler');
    //                        ^^^^^^^^^ ❌
    
    const spy = jest.spyOn(Parent.methods, 'customEventHandler')
    const parent = mount(Parent)
    

    【讨论】:

      猜你喜欢
      • 2020-01-17
      • 2021-02-04
      • 2021-07-26
      • 2021-06-14
      • 2019-10-29
      • 1970-01-01
      • 2019-04-12
      • 2020-01-01
      • 2021-11-27
      相关资源
      最近更新 更多