QA
Intermediate LevelVue JS

How do you unit test Vue 3 components using Vitest and Vue Test Utils?

❓ Interview Prompt: Explain component unit testing with Vitest, mounting components with @vue/test-utils, triggering events, and DOM assertions.

Vitest is the standard fast unit test runner for Vite projects, pairing seamlessly with '@vue/test-utils'.

Essential Test Workflow:

1
Mounting: Use 'mount(Component, { props: {...} })' to render component into Virtual DOM wrapper.
2
Interacting: Trigger user interactions asynchronously using 'await wrapper.find("button").trigger("click")'.
3
Asserting: Assert DOM text or emitted events: 'expect(wrapper.emitted("submit")).toBeTruthy()'.

Code Implementation Example

javascript
import { test, expect } from 'vitest';
import { mount } from '@vue/test-utils';
import Counter from '@/components/Counter.vue';

test('increments counter on button click', async () => {
  const wrapper = mount(Counter, { props: { initialCount: 5 } });

  expect(wrapper.text()).toContain('Count: 5');

  // Trigger button click asynchronously
  await wrapper.find('button').trigger('click');

  expect(wrapper.text()).toContain('Count: 6');
});
💡Unit testing a Vue 3 counter component using Vitest and Vue Test Utils.
🎯 Interview Key Takeaway

Use Vitest and @vue/test-utils mount() to render components, trigger async user events, and assert DOM output.

#Vitest#Testing#Vue Test Utils#Intermediate
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?