Testing Dom events in Vue.js using Jest and vue-test-utils
In this tutorial, we are going to learn about how to test native dom events in vue using jest and vue-test-utils library.
Native dom events are happening in the browser when we click on button
or hovering a mouse on the element, In Vue.js we can respond to the dom events by adding event handler methods to the element by using v-on
directive or @
syntax.
The example component we are testing.
<template> <div> <h1>{{count}}</h1> <button @click="increment">Increment</button> </div> </template> <script> export default { data: function() { return { count:0 }; }, methods: { increment() { this.count++; } } }; </script>
In the above component, we created a counter
which increments it’s count
value by clicking a button.
Writing tests for dom events
In vue-test-utils, every wrapper object contains a trigger
method by using that we can trigger dom events.
Let’s write tests for our Counter
component.
import { shallowMount } from '@vue/test-utils'; import Post from '../src/components/Counter.vue' describe('Testing native dom events', () => { const wrapper = shallowMount(Post); it('calls increment method when button is clicked', () => { const increment = jest.fn(); // mock function // updating method with mock function wrapper.setMethods({ increment }); //find the button and trigger click event wrapper.find('button').trigger('click'); expect(increment).toBeCalled(); }) })
In the above code, we first created a mock function called increment
and updated the component method with the mock function by using wrapper.setMethods()
.
At final we trigger the click
event on the button element and asserting that increment
mock function was called.