Event Handling
Vue components interact with each other via props and by emitting events by calling
$emit
. In this guide, we look at how to verify events are correctly emitted using the
emitted()
function.
This article is also available as a short video .
The Counter component
Here is a simple
<Counter>
component. It features a button that, when clicked, increments an internal count variable and emits its value:
To fully test this component, we should verify that an
increment
event with the latest
count
value is emitted.
Asserting the emitted events
To do so, we will rely on the
emitted()
method. It
returns an object with all the events the component has emitted
, and their arguments in an array. Let's see how it works:
If you haven't seen
trigger()
before, don't worry. It's used to simulate user interaction. You can learn more in Forms .
The first thing to notice is that
emitted()
returns an object, where each key matches an emitted event. In this case,
increment
.
This test should pass. We made sure we emitted an event with the appropriate name.
Asserting the arguments of the event
This is good - but we can do better! We need to check that we emit the right arguments when
this.$emit('increment', this.count)
is called.
Our next step is to assert that the event contains the
count
value. We do so by passing an argument to
emitted()
.
Let's recap and break down the output of
emitted()
. Each of these keys contains the different values emitted during the test:
Asserting complex events
Imagine that now our
<Counter>
component needs to emit an object with additional information. For instance, we need to tell any parent component listening to the
@increment
event if
count
is even or odd:
As we did before, we need to trigger the
click
event on the
<button>
element. Then, we use
emitted('increment')
to make sure the right values are emitted.