简体   繁体   中英

VueJs 3 / Composition API and Jest - testing input component event emitting

I seem to be struggling trying to test VueJs 3 input component event emitting - here's what I have:

TextInput

<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']);
  });
})

Running the test I'm getting the following error

● 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 | });

When console logging emitted I get an empty object {} .

I've finally managed to find the fix reading one of the answers here Issues during testing #202

What I needed to do was to instruct Vue to use composition api and slightly amend my assertions.

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']);
  });
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM