Vue Testing Utils
БесплатноБез исполняемых скриптовНе проверенTest Vue 3 components with Vue Test Utils and Vitest — mount vs shallowMount, finding and triggering DOM, asserting props and emitted events, awaiting async…
от PramodDutta★ 253 звезды на GitHubОб этом скилле
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 forshallowMountrarely. 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.vminternals or assert onrefvalues; those tests survive refactors only by accident. awaitevery interaction. Vue batches DOM updates;trigger,setValue, andsetPropsall return promises that resolve after the next tick. A missingawaitasserts against the stale DOM.- Use
data-testidor 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(' [email protected] ');
await wrapper.get('[data-testid="password"]').setValue('hunter2hunter2');
await wrapper.get('form').trigger('submit.prevent');
expect(wrapper.emitted('submit')).toEqual([
[{ email: '[email protected]', 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);
awai
Установить Vue Testing Utils в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Vue Testing Utils?
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.
Как установить скилл Vue Testing Utils?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Vue Testing Utils запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic