Vue Testing Utils
This skill makes an AI agent write Vue 3 component tests with @vue/test-utils on Vitest: mounting with props and slots, querying via data-testid, triggering events and awaiting the render queue, asserting emitted() payloads, and wiring createTestingPinia and mocked routers through global.plugins. Trigger it on any Vue 3 + Vite project where components need unit or integration tests.
Core Principles
- Default to
mount, reach for shallowMount rarely. Stubbing all children tests a skeleton, not the component. Shallow-render only when a child is genuinely heavy (charts, maps) — and stub that one child explicitly instead.
- Test the rendered contract: props in, DOM and emitted events out. Never reach into
wrapper.vm internals or assert on ref values; those tests survive refactors only by accident.
await every interaction. Vue batches DOM updates; trigger, setValue, and setProps all return promises that resolve after the next tick. A missing await asserts against the stale DOM.
- Use
data-testid or roles, not class selectors. Tailwind/scoped-CSS classes change with styling work; test IDs change only when behavior does.
- Emitted events are the component's API — assert names and payloads.
wrapper.emitted('save') returns the calls array; check both that it fired and what it carried.
- Real Pinia logic, fake server. With
createTestingPinia({ stubActions: false }) plus mocked HTTP you test store-component integration honestly; stubbed actions are for pure-render tests only.
Setup
npm install --save-dev @vue/test-utils vitest jsdom @pinia/testing @vitejs/plugin-vue
// vitest.config.ts
import vue from '@vitejs/plugin-vue';
import { defineConfig } from 'vitest/config';
export default defineConfig({
plugins: [vue()],
test: {
environment: 'jsdom',
include: ['src/**/*.test.ts'],
restoreMocks: true,
},
});
A component worth testing:
<!-- src/components/QuantityPicker.vue -->
<script setup lang="ts">
import { computed } from 'vue';
const props = withDefaults(defineProps<{ modelValue: number; max?: number }>(), { max: 10 });
const emit = defineEmits<{ 'update:modelValue': [value: number] }>();
const atMax = computed(() => props.modelValue >= props.max);
function increment(): void {
if (!atMax.value) emit('update:modelValue', props.modelValue + 1);
}
</script>
<template>
<div>
<span data-testid="qty">{{ modelValue }}</span>
<button data-testid="inc" :disabled="atMax" @click="increment">+</button>
</div>
</template>
The test:
// src/components/QuantityPicker.test.ts
import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import QuantityPicker from './QuantityPicker.vue';
describe('QuantityPicker', () => {
it('emits update:modelValue with the incremented quantity', async () => {
const wrapper = mount(QuantityPicker, { props: { modelValue: 2 } });
await wrapper.find('[data-testid="inc"]').trigger('click');
expect(wrapper.emitted('update:modelValue')).toEqual([[3]]);
});
it('disables the button at max and emits nothing on click', async () => {
const wrapper = mount(QuantityPicker, { props: { modelValue: 5, max: 5 } });
const button = wrapper.find('[data-testid="inc"]');
expect(button.attributes('disabled')).toBeDefined();
await button.trigger('click');
expect(wrapper.emitted('update:modelValue')).toBeUndefined();
});
it('re-renders when the parent updates the prop', async () => {
const wrapper = mount(QuantityPicker, { props: { modelValue: 1 } });
await wrapper.setProps({ modelValue: 7 });
expect(wrapper.get('[data-testid="qty"]').text()).toBe('7');
});
});
Patterns
Forms with setValue and v-model
import { mount } from '@vue/test-utils';
import { expect, it } from 'vitest';
import LoginForm from './LoginForm.vue';
it('submits trimmed credentials as the submit event payload', async () => {
const wrapper = mount(LoginForm);
await wrapper.get('[data-testid="email"]').setValue(' mira@example.com ');
await wrapper.get('[data-testid="password"]').setValue('hunter2hunter2');
await wrapper.get('form').trigger('submit.prevent');
expect(wrapper.emitted('submit')).toEqual([
[{ email: 'mira@example.com', password: 'hunter2hunter2' }],
]);
});
Async Components: flushPromises after Mocked Fetch
import { flushPromises, mount } from '@vue/test-utils';
import { expect, it, vi } from 'vitest';
import SkillList from './SkillList.vue';
import * as api from '../api/skills';
it('renders fetched skills after the loading state', async () => {
vi.spyOn(api, 'fetchSkills').mockResolvedValue([
{ slug: 'vitest-testing', name: 'Vitest' },
{ slug: 'msw-mocking', name: 'MSW' },
]);
const wrapper = mount(SkillList);
expect(wrapper.find('[data-testid="spinner"]').exists()).toBe(true);
await flushPromises(); // resolves the fetch AND the subsequent render
expect(wrapper.find('[data-testid="spinner"]').exists()).toBe(false);
expect(wrapper.findAll('[data-testid="skill-row"]')).toHaveLength(2);
expect(wrapper.text()).toContain('Vitest');
});
Pinia Stores with createTestingPinia
import { createTestingPinia } from '@pinia/testing';
import { mount } from '@vue/test-utils';
import { expect, it, vi } from 'vitest';
import CartBadge from './CartBadge.vue';
import { useCartStore } from '../stores/cart';
it('shows the item count from the store and calls clear on click', async () => {
const wrapper = mount(CartBadge, {
global: {
plugins: [
createTestingPinia({
createSpy: vi.fn,
initialState: { cart: { items: [{ sku: 'A1' }, { sku: 'B2' }] } },
}),
],
},
});
const store = useCartStore(); // the same instance the component uses
expect(wrapper.get('[data-testid="count"]').text()).toBe('2');
await wrapper.get('[data-testid="clear"]').trigger('click');
expect(store.clear).toHaveBeenCalledOnce(); // actions auto-stubbed as spies
});
Router: Mock It, Do Not Mount It
import { mount } from '@vue/test-utils';
import { expect, it, vi } from 'vitest';
import SkillCard from './SkillCard.vue';
it('navigates to the skill detail page on card click', async () => {
const push = vi.fn();
const wrapper = mount(SkillCard, {
props: { slug: 'supertest-api', name: 'SuperTest' },
global: {
mocks: { $router: { push } },
stubs: { RouterLink: { template: '<a><slot /></a>' } },
},
});
await wrapper.get('[data-testid="card"]').trigger('click');
expect(push).toHaveBeenCalledWith({ name: 'skill-detail', params: { slug: 'supertest-api' } });
});
Slots and Scoped Slots
import { mount } from '@vue/test-utils';
import { expect, it } from 'vitest';
import DataTable from './DataTable.vue';
it('renders the scoped row slot with each item', () => {
const wrapper = mount(DataTable, {
props: { items: [{ id: 1, name: 'alpha' }] },
slots: {
row: `<template #row="{ item }"><td data-testid="cell">{{ item.name }}</td></template>`,
},
});
expect(wrapper.get('[data-testid="cell"]').text()).toBe('alpha');
});
Best Practices
- Use
wrapper.get() when the element must exist (throws with a clear message); wrapper.find() + .exists() only for asserting absence.
- Share mount defaults via a factory:
const factory = (props = {}) => mount(Comp, { props: { ...defaults, ...props } }) — not via a mutable module-level wrapper.
- Assert
emitted() payload equality on the whole calls array (toEqual([[3]])) to catch double-fires for free.
- For components using
<Teleport>, target the teleport destination with document.querySelector or stub teleport with global.stubs: { teleport: true }.
- Test accessibility-relevant output:
attributes('aria-expanded'), attributes('disabled') — these are behavior, not styling.
- Keep one component per test file mounted fresh per test;
restoreMocks: true plus fresh mounts eliminates 90% of cross-test pollution.
Anti-Patterns
wrapper.vm.someRef = 5 to set state. Mutating internals bypasses the component contract; drive state through props, interactions, or store initial state.
- Missing
await on trigger/setValue/setProps. The assertion sees the previous DOM and passes or fails for the wrong reason.
shallowMount as the default everywhere. Stub names in snapshots (<child-component-stub>) verify nothing about integration.
- Mounting the full real router and
await router.isReady() for a unit test. Mock $router.push instead; real-router tests belong in a small dedicated navigation suite.
- Asserting CSS classes as behavior (
expect(wrapper.classes()).toContain('text-red-500')). Assert the state that drives the class (aria-invalid, emitted validation event) instead.
- One
beforeEach that mounts with a kitchen-sink global config for every test in the file — slot, store, and router config should appear in the tests that need them.
When to Trigger This Skill
- A Vue 3 project needs component tests, or
@vue/test-utils is in devDependencies.
- The user asks how to test props, emits, v-model, slots, or async data fetching in a Vue component.
- Tests are flaky from missing
await/flushPromises or pollute each other through shared wrappers.
- Components depend on Pinia or Vue Router and the user needs them mocked or stubbed in tests.
- Migrating Vue 2 (
createLocalVue, propsData) tests to the Vue 3 global/props API.
1---2name: vue-testing-utils3description: Test Vue 3 components with Vue Test Utils and Vitest — mount vs shallowMount, finding and triggering DOM, asserting props and emitted events, awaiting async updates, and mocking Pinia stores and Vue Router.4version: 1.0.05author: thetestingacademy6license: MIT7tags: [vue, vue-test-utils, component-testing, vitest, pinia, vue-router, jsdom, unit-testing, emits]8testingTypes: [unit, integration]9frameworks: [vue-test-utils, vitest, vue]10languages: [typescript, javascript]11domains: [web]12agents: [claude-code, cursor, github-copilot, windsurf, codex, aider, continue, cline, zed, bolt, gemini-cli, amp]13metadata:14 source: https://skillmd.com/skills/pramoddutta/vue-testing-utils15---1617# Vue Testing Utils1819This skill makes an AI agent write Vue 3 component tests with `@vue/test-utils` on Vitest: mounting with props and slots, querying via `data-testid`, triggering events and awaiting the render queue, asserting `emitted()` payloads, and wiring `createTestingPinia` and mocked routers through `global.plugins`. Trigger it on any Vue 3 + Vite project where components need unit or integration tests.2021## Core Principles22231. **Default to `mount`, reach for `shallowMount` rarely.** Stubbing all children tests a skeleton, not the component. Shallow-render only when a child is genuinely heavy (charts, maps) — and stub that one child explicitly instead.242. **Test the rendered contract: props in, DOM and emitted events out.** Never reach into `wrapper.vm` internals or assert on `ref` values; those tests survive refactors only by accident.253. **`await` every interaction.** Vue batches DOM updates; `trigger`, `setValue`, and `setProps` all return promises that resolve after the next tick. A missing `await` asserts against the stale DOM.264. **Use `data-testid` or roles, not class selectors.** Tailwind/scoped-CSS classes change with styling work; test IDs change only when behavior does.275. **Emitted events are the component's API — assert names and payloads.** `wrapper.emitted('save')` returns the calls array; check both that it fired and what it carried.286. **Real Pinia logic, fake server.** With `createTestingPinia({ stubActions: false })` plus mocked HTTP you test store-component integration honestly; stubbed actions are for pure-render tests only.2930## Setup3132```bash33npm install --save-dev @vue/test-utils vitest jsdom @pinia/testing @vitejs/plugin-vue34```3536```typescript37// vitest.config.ts38import vue from '@vitejs/plugin-vue';39import { defineConfig } from 'vitest/config';4041export default defineConfig({42 plugins: [vue()],43 test: {44 environment: 'jsdom',45 include: ['src/**/*.test.ts'],46 restoreMocks: true,47 },48});49```5051A component worth testing:5253```vue54<!-- src/components/QuantityPicker.vue -->55<script setup lang="ts">56import { computed } from 'vue';5758const props = withDefaults(defineProps<{ modelValue: number; max?: number }>(), { max: 10 });59const emit = defineEmits<{ 'update:modelValue': [value: number] }>();6061const atMax = computed(() => props.modelValue >= props.max);6263function increment(): void {64 if (!atMax.value) emit('update:modelValue', props.modelValue + 1);65}66</script>6768<template>69 <div>70 <span data-testid="qty">{{ modelValue }}</span>71 <button data-testid="inc" :disabled="atMax" @click="increment">+</button>72 </div>73</template>74```7576The test:7778```typescript79// src/components/QuantityPicker.test.ts80import { mount } from '@vue/test-utils';81import { describe, expect, it } from 'vitest';82import QuantityPicker from './QuantityPicker.vue';8384describe('QuantityPicker', () => {85 it('emits update:modelValue with the incremented quantity', async () => {86 const wrapper = mount(QuantityPicker, { props: { modelValue: 2 } });8788 await wrapper.find('[data-testid="inc"]').trigger('click');8990 expect(wrapper.emitted('update:modelValue')).toEqual([[3]]);91 });9293 it('disables the button at max and emits nothing on click', async () => {94 const wrapper = mount(QuantityPicker, { props: { modelValue: 5, max: 5 } });95 const button = wrapper.find('[data-testid="inc"]');9697 expect(button.attributes('disabled')).toBeDefined();98 await button.trigger('click');99 expect(wrapper.emitted('update:modelValue')).toBeUndefined();100 });101102 it('re-renders when the parent updates the prop', async () => {103 const wrapper = mount(QuantityPicker, { props: { modelValue: 1 } });104 await wrapper.setProps({ modelValue: 7 });105 expect(wrapper.get('[data-testid="qty"]').text()).toBe('7');106 });107});108```109110## Patterns111112### Forms with setValue and v-model113114```typescript115import { mount } from '@vue/test-utils';116import { expect, it } from 'vitest';117import LoginForm from './LoginForm.vue';118119it('submits trimmed credentials as the submit event payload', async () => {120 const wrapper = mount(LoginForm);121122 await wrapper.get('[data-testid="email"]').setValue(' mira@example.com ');123 await wrapper.get('[data-testid="password"]').setValue('hunter2hunter2');124 await wrapper.get('form').trigger('submit.prevent');125126 expect(wrapper.emitted('submit')).toEqual([127 [{ email: 'mira@example.com', password: 'hunter2hunter2' }],128 ]);129});130```131132### Async Components: flushPromises after Mocked Fetch133134```typescript135import { flushPromises, mount } from '@vue/test-utils';136import { expect, it, vi } from 'vitest';137import SkillList from './SkillList.vue';138import * as api from '../api/skills';139140it('renders fetched skills after the loading state', async () => {141 vi.spyOn(api, 'fetchSkills').mockResolvedValue([142 { slug: 'vitest-testing', name: 'Vitest' },143 { slug: 'msw-mocking', name: 'MSW' },144 ]);145146 const wrapper = mount(SkillList);147 expect(wrapper.find('[data-testid="spinner"]').exists()).toBe(true);148149 await flushPromises(); // resolves the fetch AND the subsequent render150151 expect(wrapper.find('[data-testid="spinner"]').exists()).toBe(false);152 expect(wrapper.findAll('[data-testid="skill-row"]')).toHaveLength(2);153 expect(wrapper.text()).toContain('Vitest');154});155```156157### Pinia Stores with createTestingPinia158159```typescript160import { createTestingPinia } from '@pinia/testing';161import { mount } from '@vue/test-utils';162import { expect, it, vi } from 'vitest';163import CartBadge from './CartBadge.vue';164import { useCartStore } from '../stores/cart';165166it('shows the item count from the store and calls clear on click', async () => {167 const wrapper = mount(CartBadge, {168 global: {169 plugins: [170 createTestingPinia({171 createSpy: vi.fn,172 initialState: { cart: { items: [{ sku: 'A1' }, { sku: 'B2' }] } },173 }),174 ],175 },176 });177 const store = useCartStore(); // the same instance the component uses178179 expect(wrapper.get('[data-testid="count"]').text()).toBe('2');180181 await wrapper.get('[data-testid="clear"]').trigger('click');182 expect(store.clear).toHaveBeenCalledOnce(); // actions auto-stubbed as spies183});184```185186### Router: Mock It, Do Not Mount It187188```typescript189import { mount } from '@vue/test-utils';190import { expect, it, vi } from 'vitest';191import SkillCard from './SkillCard.vue';192193it('navigates to the skill detail page on card click', async () => {194 const push = vi.fn();195 const wrapper = mount(SkillCard, {196 props: { slug: 'supertest-api', name: 'SuperTest' },197 global: {198 mocks: { $router: { push } },199 stubs: { RouterLink: { template: '<a><slot /></a>' } },200 },201 });202203 await wrapper.get('[data-testid="card"]').trigger('click');204205 expect(push).toHaveBeenCalledWith({ name: 'skill-detail', params: { slug: 'supertest-api' } });206});207```208209### Slots and Scoped Slots210211```typescript212import { mount } from '@vue/test-utils';213import { expect, it } from 'vitest';214import DataTable from './DataTable.vue';215216it('renders the scoped row slot with each item', () => {217 const wrapper = mount(DataTable, {218 props: { items: [{ id: 1, name: 'alpha' }] },219 slots: {220 row: `<template #row="{ item }"><td data-testid="cell">{{ item.name }}</td></template>`,221 },222 });223224 expect(wrapper.get('[data-testid="cell"]').text()).toBe('alpha');225});226```227228## Best Practices229230- Use `wrapper.get()` when the element must exist (throws with a clear message); `wrapper.find()` + `.exists()` only for asserting absence.231- Share mount defaults via a factory: `const factory = (props = {}) => mount(Comp, { props: { ...defaults, ...props } })` — not via a mutable module-level wrapper.232- Assert `emitted()` payload equality on the whole calls array (`toEqual([[3]])`) to catch double-fires for free.233- For components using `<Teleport>`, target the teleport destination with `document.querySelector` or stub teleport with `global.stubs: { teleport: true }`.234- Test accessibility-relevant output: `attributes('aria-expanded')`, `attributes('disabled')` — these are behavior, not styling.235- Keep one component per test file mounted fresh per test; `restoreMocks: true` plus fresh mounts eliminates 90% of cross-test pollution.236237## Anti-Patterns238239- **`wrapper.vm.someRef = 5` to set state.** Mutating internals bypasses the component contract; drive state through props, interactions, or store initial state.240- **Missing `await` on `trigger`/`setValue`/`setProps`.** The assertion sees the previous DOM and passes or fails for the wrong reason.241- **`shallowMount` as the default everywhere.** Stub names in snapshots (`<child-component-stub>`) verify nothing about integration.242- **Mounting the full real router and `await router.isReady()` for a unit test.** Mock `$router.push` instead; real-router tests belong in a small dedicated navigation suite.243- **Asserting CSS classes as behavior** (`expect(wrapper.classes()).toContain('text-red-500')`). Assert the state that drives the class (`aria-invalid`, emitted validation event) instead.244- **One `beforeEach` that mounts with a kitchen-sink global config** for every test in the file — slot, store, and router config should appear in the tests that need them.245246## When to Trigger This Skill247248- A Vue 3 project needs component tests, or `@vue/test-utils` is in `devDependencies`.249- The user asks how to test props, emits, v-model, slots, or async data fetching in a Vue component.250- Tests are flaky from missing `await`/`flushPromises` or pollute each other through shared wrappers.251- Components depend on Pinia or Vue Router and the user needs them mocked or stubbed in tests.252- Migrating Vue 2 (`createLocalVue`, `propsData`) tests to the Vue 3 `global`/`props` API.