Розробка Unit-тестів для компонентів (Vue Test Utils)
Vue Test Utils — офіційна бібліотека для тестування Vue 3 компонентів. Працює з Vitest (рекомендується) або Jest. Монтує компонент в ізольованому окруженні, дозволяє перевіряти рендер, події та реактивність.
Налаштування (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,
},
});
Базове монтування
import { mount, shallowMount } from '@vue/test-utils';
import UserCard from './UserCard.vue';
describe('UserCard', () => {
it('відображає ім'я користувача', () => {
const wrapper = mount(UserCard, {
props: { user: { name: 'Іван Петров', email: '[email protected]' } },
});
expect(wrapper.text()).toContain('Іван Петров');
expect(wrapper.find('[data-testid="email"]').text()).toBe('[email protected]');
});
it('emit delete event', async () => {
const wrapper = mount(UserCard, {
props: { user: { id: 42, name: 'Іван' } },
});
await wrapper.find('[data-testid="delete-btn"]').trigger('click');
expect(wrapper.emitted('delete')).toBeTruthy();
expect(wrapper.emitted('delete')![0]).toEqual([42]);
});
});
Тестування з Pinia store
import { setActivePinia, createPinia } from 'pinia';
import { useCartStore } from '@/stores/cart';
describe('CartButton', () => {
beforeEach(() => {
setActivePinia(createPinia());
});
it('додає товар в кошик', 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);
});
});
Тестування асинхронних компонентів
it('загружує та відображає дані', async () => {
vi.mock('@/api', () => ({
fetchUser: vi.fn().mockResolvedValue({ name: 'Марія' }),
}));
const wrapper = mount(UserProfile, { props: { userId: 1 } });
// Чекаємо завантаження
expect(wrapper.find('[data-testid="loading"]').exists()).toBe(true);
await flushPromises(); // з '@vue/test-utils'
expect(wrapper.find('[data-testid="loading"]').exists()).toBe(false);
expect(wrapper.text()).toContain('Марія');
});
Тестування слотів
it('відображає default slot', () => {
const wrapper = mount(Card, {
slots: {
default: '<p data-testid="slotted">Вміст</p>',
header: 'Заголовок карточки',
},
});
expect(wrapper.find('[data-testid="slotted"]').exists()).toBe(true);
expect(wrapper.find('.card-header').text()).toBe('Заголовок карточки');
});
Стабы для дочірніх компонентів
// shallowMount — автоматично стабирує дочірні компоненти
const wrapper = shallowMount(ParentComponent);
// Дочірні компоненти рендерятся як <child-component-stub>
// Явні стабы
const wrapper = mount(ParentComponent, {
global: {
stubs: {
BaseIcon: { template: '<span></span>' },
RouterLink: { template: '<a><slot /></a>' },
},
},
});
Тестування composables
// composables/useForm.test.ts
import { useForm } from './useForm';
test('валідує поле email', () => {
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('Введіть коректний email');
});
Часовий графік
Налаштування + написання тестів для 20–30 компонентів існуючого Vue-проекту: 4–7 днів.







