A
A
Alexey Nikolaev2020-02-13 12:57:02
Unit testing
Alexey Nikolaev, 2020-02-13 12:57:02

How can I mock preventDefault on vm.$emit in Jest and vue-test-utils?

Good day.
There is a simple component that looks something like this.

<template>
  <v-link
    href="#"
    data-test="send-code"
    @click.prevent="onClick"
  >
    {{ label }}
  </v-link>
</template>

<script>
import VLink from '@vendor/ui/kit/VLink';

export default {
  name: 'SendCode',

  methods: {
    onClick() {
      // some stuff
      this.$emit('click');
    },
  },

  components: {
    VLink,
  },
};
</script>

Its essence is that when the link is clicked, the "click" event is emitted, and both the internal mechanisms of the component and the external handler, which is passed in the props, are triggered. Now we have added a condition under which the link (v-link) is hidden for 60 seconds after the click. Need to test.

Testing with us via vue-test-utils + jest. Actually, what I check is that I first do vm.$emit('click') to check that when the link is clicked, the handler is called at all (which emits click one level higher). However, attention is the essence of the task, the test immediately fails with the message "TypeError: Cannot read property 'preventDefault' of undefined". This is due to the "prevent" modifier.
wrapper.find('[data-test=send-code]').vm.$emit('click'); // fail! если убрать prevent, все заработает


I don't want to remove the modifier. You can, of course, remove it and make preventDefault manually, and in the test pass a fake object with preventDefault inside, but this looks like a crutch, plus you shouldn’t adjust the code to fit the tests.

How to be? Is it possible to somehow mock calls to preventDefault, best at the global level?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2020-02-13
@Aetae

I think you are doing something wrong.
When simulating a click, it is obviously worth passing a full-fledged event object, at least like this: Events are not in themselves, the code from the event can take a lot.
$emit('click', new MouseEvent('click'))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question