【问题标题】:VueJs 3 / Composition API and Jest - testing input component event emittingVueJs 3 / Composition API 和 Jest - 测试输入组件事件发射
【发布时间】:2020-09-24 18:27:57
【问题描述】:

我似乎在努力测试 VueJs 3 输入组件事件发射 - 这就是我所拥有的:

文本输入

<template>
  <input v-model="input" />
</template>
<script>
import { watch } from '@vue/composition-api';
export default {
  name: 'TextInput',
  props: {
    value: {
      default: '',
    },
  },
  setup (props, { emit }) {
    let input = ref(props.value);
    watch(input, value => {
      emit('input', value);
    });
    return { input };
  }
};
</script>

text-input.spec.js

import { shallowMount } from '@vue/test-utils';
import { TextInput } from '@/src/index';

describe('TextInput test', () => {
  it('Emits input event', async () => {
    const wrapper = shallowMount(TextInput);

    const input = wrapper.find('input');
    input.setValue('Jon');
    input.trigger('keyup');

    await wrapper.vm.$nextTick();

    const emitted = wrapper.emitted('input');

    expect(emitted).toHaveLength(1);
    expect(emitted).toEqual(['Jon']);
  });
})

运行测试我收到以下错误

● TextInput test › Emits input event

    expect(received).toHaveLength(expected)

    Matcher error: received value must have a length property whose value must be a number

    Received has value: undefined

      52 |     const triggeredEvent = wrapper.emitted('input');
      53 |
    > 54 |     expect(triggeredEvent).toHaveLength(1);
         |                            ^
      55 |     expect(triggeredEvent).toEqual(['Jon']);
      56 |   });
      57 | });

当控制台记录 emitted 时,我得到一个空对象 {}。

【问题讨论】:

    标签: javascript vue.js jestjs vue-composition-api vuejs3


    【解决方案1】:

    我终于在Issues during testing #202这里找到了答案之一

    我需要做的是指示 Vue 使用组合 API 并稍微修改我的断言。

    import Vue from 'vue';
    import { TextInput } from '@/src/index';
    import { shallowMount } from '@vue/test-utils';
    import CompositionApi from '@vue/composition-api';
    
    Vue.use(CompositionApi);
    
    describe('TextInput test', () => {
      it('Emits input event', async () => {
        const wrapper = shallowMount(TextInput);
    
        const input = wrapper.find('input');
        input.setValue('Jon');
        input.trigger('keyup');
    
        await wrapper.vm.$nextTick();
    
        const emitted = wrapper.emitted('input');
    
        expect(emitted).toHaveLength(2);
        expect(emitted[1]).toEqual(['Jon']);
      });
    })
    

    【讨论】:

      猜你喜欢
      • 2022-11-29
      • 2020-01-27
      • 2021-12-08
      • 2021-05-31
      • 2021-02-12
      • 2021-03-24
      • 2019-05-01
      • 2021-02-04
      • 2020-03-08
      相关资源
      最近更新 更多