← Back to all snippets
JAVASCRIPT

Unit Testing Vue 3 Components with Vue Test Utils

Learn how to write effective unit tests for your Vue 3 components using Vue Test Utils and a testing framework like Vitest, ensuring component reliability.

// MyComponent.vue
<template>
  <button @click="increment">Count: {{ count }}</button>
</template>

<script setup>
import { ref } from 'vue';

const count = ref(0);

const increment = () => {
  count.value++;
};
</script>


// MyComponent.test.js
import { mount } from '@vue/test-utils';
import { describe, it, expect } from 'vitest';
import MyComponent from './MyComponent.vue';

describe('MyComponent', () => {
  it('renders correctly and increments count on click', async () => {
    const wrapper = mount(MyComponent);

    // Check initial state
    expect(wrapper.text()).toContain('Count: 0');

    // Simulate a click
    await wrapper.find('button').trigger('click');

    // Check updated state
    expect(wrapper.text()).toContain('Count: 1');

    // Simulate another click
    await wrapper.find('button').trigger('click');
    expect(wrapper.text()).toContain('Count: 2');
  });

  it('checks if the increment method updates the count', async () => {
    const wrapper = mount(MyComponent);
    
    // Directly access the component instance and call its method (if exposed)
    // For setup components, methods are usually exposed implicitly or via defineExpose
    // In this case, we test via user interaction, which is preferred for unit tests.
    
    // Alternative (less common for setup components unless explicitly exposed):
    // await wrapper.vm.increment(); // This might not work directly for setup components
    // expect(wrapper.text()).toContain('Count: 1');
  });
});
How it works: This snippet demonstrates how to unit test a basic Vue 3 component using Vue Test Utils and Vitest. The `mount` function renders the component into a virtual DOM. You can then use `wrapper.find` to locate elements and `trigger` to simulate user interactions like clicks. `expect` assertions verify the component's rendered output or internal state after actions, ensuring it behaves as expected. This approach helps catch regressions and ensures component reliability.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs