0
0
Vueframework~5 mins

Testing user interactions in Vue

Choose your learning style9 modes available
Introduction

Testing user interactions helps make sure your app works as expected when people click buttons or type in fields. It catches mistakes early so users have a smooth experience.

You want to check if clicking a button changes the page content correctly.
You need to verify that typing in a form input updates the data shown.
You want to confirm that toggling a checkbox shows or hides some text.
You want to make sure a dropdown menu opens when clicked.
You want to test that submitting a form triggers the right action.
Syntax
Vue
import { mount } from '@vue/test-utils'
import Component from './Component.vue'

test('description', async () => {
  const wrapper = mount(Component)
  await wrapper.find('selector').trigger('event')
  expect(wrapper.text()).toContain('expected text')
})

Use mount to load the component for testing.

Use trigger to simulate user events like clicks or typing.

Examples
Simulates clicking a button and checks if the text changes to 'Clicked!'.
Vue
await wrapper.find('button').trigger('click')
expect(wrapper.text()).toContain('Clicked!')
Simulates typing 'Hello' into an input field and checks the input's value.
Vue
await wrapper.find('input').setValue('Hello')
expect(wrapper.find('input').element.value).toBe('Hello')
Simulates checking a checkbox and verifies the text updates accordingly.
Vue
await wrapper.find('input[type=checkbox]').setChecked(true)
expect(wrapper.text()).toContain('Checked!')
Sample Program

This test loads the ButtonClick component, checks that the message is not visible initially, then simulates a button click and confirms the message appears.

Vue
/* ButtonClick.vue */
<template>
  <button @click="clicked = true">Click me</button>
  <p v-if="clicked">Button was clicked!</p>
</template>

<script setup>
import { ref } from 'vue'
const clicked = ref(false)
</script>

/* ButtonClick.test.js */
import { mount } from '@vue/test-utils'
import ButtonClick from './ButtonClick.vue'

test('shows message after button click', async () => {
  const wrapper = mount(ButtonClick)
  expect(wrapper.text()).not.toContain('Button was clicked!')
  await wrapper.find('button').trigger('click')
  expect(wrapper.text()).toContain('Button was clicked!')
})
OutputSuccess
Important Notes

Always wait for Vue to update the DOM after events using await.

Use clear selectors like element tags or classes to find elements.

Test only one interaction per test to keep tests simple and clear.

Summary

Testing user interactions means simulating clicks, typing, and other actions.

Use Vue Test Utils mount and trigger to do this.

Check the component output to confirm it reacts correctly.