Developing Unit Tests for Components (Vue Test Utils)
Vue Test Utils—official library for testing Vue 3 components. Works with Vitest (recommended) or Jest. Mounts component in isolated environment, lets you check rendering, events and reactivity.
Setup (Vue 3 + Vitest)
npm install -D @vue/test-utils vitest jsdom @vitejs/plugin-vue
// vitest.config.ts
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
test: {
environment: 'jsdom',
globals: true,
},
});
Basic Mounting
import { mount, shallowMount } from '@vue/test-utils';
import UserCard from './UserCard.vue';
describe('UserCard', () => {
it('renders user name', () => {
const wrapper = mount(UserCard, {
props: { user: { name: 'John Doe', email: '[email protected]' } },
});
expect(wrapper.text()).toContain('John Doe');
expect(wrapper.find('[data-testid="email"]').text()).toBe('[email protected]');
});
it('emits delete event', async () => {
const wrapper = mount(UserCard, {
props: { user: { id: 42, name: 'John' } },
});
await wrapper.find('[data-testid="delete-btn"]').trigger('click');
expect(wrapper.emitted('delete')).toBeTruthy();
expect(wrapper.emitted('delete')![0]).toEqual([42]);
});
});
Testing with Pinia Store
import { setActivePinia, createPinia } from 'pinia';
import { useCartStore } from '@/stores/cart';
describe('CartButton', () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it('adds item to cart', async () => {
const wrapper = mount(CartButton, {
props: { productId: 1 },
global: { plugins: [createPinia()] },
});
const store = useCartStore();
expect(store.items).toHaveLength(0);
await wrapper.find('button').trigger('click');
expect(store.items).toHaveLength(1);
});
});
Testing Async Components
it('loads and displays data', async () => {
vi.mock('@/api', () => ({
fetchUser: vi.fn().mockResolvedValue({ name: 'Maria' }),
}));
const wrapper = mount(UserProfile, { props: { userId: 1 } });
// Wait for loading
expect(wrapper.find('[data-testid="loading"]').exists()).toBe(true);
await flushPromises(); // from '@vue/test-utils'
expect(wrapper.find('[data-testid="loading"]').exists()).toBe(false);
expect(wrapper.text()).toContain('Maria');
});
Testing Slots
it('renders default slot', () => {
const wrapper = mount(Card, {
slots: {
default: '<p data-testid="slotted">Content</p>',
header: 'Card Header',
},
});
expect(wrapper.find('[data-testid="slotted"]').exists()).toBe(true);
expect(wrapper.find('.card-header').text()).toBe('Card Header');
});
Stubs for Child Components
// shallowMount—automatically stubs child components
const wrapper = shallowMount(ParentComponent);
// Child components render as <child-component-stub>
// Explicit stubs
const wrapper = mount(ParentComponent, {
global: {
stubs: {
BaseIcon: { template: '<span></span>' },
RouterLink: { template: '<a><slot /></a>' },
},
},
});
Testing Composables
// composables/useForm.test.ts
import { useForm } from './useForm';
test('validates email field', () => {
const { fields, validate } = useForm({
email: { value: '', rules: ['required', 'email'] },
});
fields.email.value = 'not-an-email';
const isValid = validate();
expect(isValid).toBe(false);
expect(fields.email.error).toBe('Enter valid email');
});
Timeline
Setup + write tests for 20–30 components of existing Vue project: 4–7 days.







