Search⌘ K
AI Features

Custom Events

Explore how to test custom events in Vue.js components using Jest. Understand how to assert event triggers, test event handlers with mocks and spies, and verify event emissions to ensure your components communicate correctly.

Custom Events

We can test at least two things in Custom Events:

  • Asserting that after an action, an event gets triggered
  • Checking what an event listener calls when it gets triggered

In the case of the MessageList.vue and Message.vue components example, that gets translated to:

  • Asserting that Message components trigger a message-clicked when a message gets clicked
  • Checking that when a message-clicked occurs, a handleMessageClick function is called in MessageList

Step 1:

First, go to Message.vue and use $emit to trigger that custom event:

HTML
<template>
<li
style="margin-top: 10px"
class="message"
@click="handleClick">
{{message}}
</li>
</template>
<script>
export default {
name: "Message",
props: ["message"],
methods: {
handleClick() {
this.$emit("message-clicked", this.message)
}
}
};
</script>

Then, in ...