All skills
vuejs-ai avatar

/vue-testing-best-practices

@bc922e4 official
by Vue AIvuejs-ai/skills2.9k stars
167

Use for Vue.js testing. Covers Vitest, Vue Test Utils, component testing, mocking, testing patterns, and Playwright for E2E testing.

Use this Skill: https://skilld.dev/gh/vuejs-ai/skills/vue-testing-best-practices

This session only. Nothing lands on disk.

referencetesting-vitest-recommended-for-vue.md

≈1.3k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Use Vitest for Vue 3 Testing - Recommended by Vue Team

Impact: MEDIUM - Vitest is created and maintained by Vue/Vite team members and shares the same configuration and transform pipeline as Vite. Using Jest or other test runners with Vite-based projects requires additional configuration and can result in slower test execution and compatibility issues.

Use Vitest for new Vue 3 projects. Only consider Jest if migrating an existing test suite.

Task Checklist

  • Install Vitest and related packages for Vue testing
  • Configure vitest in vite.config.js or vitest.config.js
  • Set up proper test environment (happy-dom or jsdom)
  • Add test scripts to package.json
  • Configure globals if desired for cleaner test syntax
  • Use @vue/test-utils for component mounting

Quick Setup

# Install required packages
npm install -D vitest @vue/test-utils happy-dom
# or with jsdom
npm install -D vitest @vue/test-utils jsdom

vite.config.js:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  test: {
    // Enable global test APIs (describe, it, expect)
    globals: true,
    // Use happy-dom for faster tests (or 'jsdom' for better compatibility)
    environment: 'happy-dom',
    // Optional: Setup files for global configuration
    setupFiles: ['./src/test/setup.js']
  }
})

package.json:

{
  "scripts": {
    "test": "vitest",
    "test:run": "vitest run",
    "test:coverage": "vitest run --coverage"
  }
}

tsconfig.json (if using TypeScript):

{
  "compilerOptions": {
    "types": ["vitest/globals"]
  }
}

Test File Example

// src/components/Counter.test.js
import { describe, it, expect, beforeEach } from 'vitest'  // optional with globals: true
import { mount } from '@vue/test-utils'
import Counter from './Counter.vue'

describe('Counter', () => {
  let wrapper

  beforeEach(() => {
    wrapper = mount(Counter)
  })

  it('renders initial count', () => {
    expect(wrapper.find('[data-testid="count"]').text()).toBe('0')
  })

  it('increments when button clicked', async () => {
    await wrapper.find('[data-testid="increment"]').trigger('click')
    expect(wrapper.find('[data-testid="count"]').text()).toBe('1')
  })
})

Vitest vs Jest Comparison

Feature Vitest Jest
Vite Integration Native Requires config
Speed Very fast (ESM native) Slower with Vite
Watch Mode Excellent Good
Vue SFC Support Works with Vite Needs vue-jest
Config Sharing Same as vite.config Separate
API Jest-compatible Standard

Using with Testing Library

npm install -D @testing-library/vue @testing-library/jest-dom
// src/test/setup.js
import { expect } from 'vitest'
import * as matchers from '@testing-library/jest-dom/matchers'

expect.extend(matchers)
// Component.test.js
import { render, screen, fireEvent } from '@testing-library/vue'
import UserCard from './UserCard.vue'

test('displays user name', () => {
  render(UserCard, {
    props: { name: 'John Doe' }
  })

  expect(screen.getByText('John Doe')).toBeInTheDocument()
})

Advanced Configuration

// vitest.config.js (separate file if preferred)
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  test: {
    globals: true,
    environment: 'happy-dom',
    include: ['**/*.{test,spec}.{js,ts,jsx,tsx}'],
    exclude: ['node_modules', 'dist', 'e2e'],
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
      exclude: ['node_modules', 'test']
    },
    // Helpful for debugging
    reporters: ['verbose'],
    // Run tests in sequence in CI
    poolOptions: {
      threads: {
        singleThread: process.env.CI === 'true'
      }
    }
  }
})

Common Patterns

Mocking Modules

import { vi } from 'vitest'

vi.mock('@/api/users', () => ({
  fetchUser: vi.fn().mockResolvedValue({ name: 'John' })
}))

Testing with Fake Timers

import { vi, beforeEach, afterEach } from 'vitest'

beforeEach(() => {
  vi.useFakeTimers()
})

afterEach(() => {
  vi.restoreAllMocks()
})

test('debounced search', async () => {
  const wrapper = mount(SearchBox)
  await wrapper.find('input').setValue('vue')

  vi.advanceTimersByTime(300)
  await flushPromises()

  expect(wrapper.emitted('search')).toBeTruthy()
})

Reference

Source: SKILL.md on GitHub

No alerts16d5 checks · Risk SAFE
  • Gen Agent Trust Hub16d

    The skill provides standard documentation, configuration guidelines, and best practices for testing Vue 3 applications with Vitest, Vue Test Utils, and Playwright. No security vulnerabilities or malicious patterns were detected.

  • Socket16d

    No alerts

  • Snyk16d

    Risk: LOW · No issues

  • Runlayer7mo

    1/12 files flagged

  • ZeroLeaks5mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at bc922e4. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 2 months ago.

Steadyupdated 8 months ago
version
1.0.0
author
github.com/vuejs-ai
  • Vue
  • Testing
  • vitest
  • vue-test-utils
  • playwright
  • e2e
  • composables
  • pinia
  • mocking

README badge

README badge for vuejs-ai/skills/vue-testing-best-practices

Instructs Claude on Vue 3 testing patterns using Vitest, Vue Test Utils, and Playwright, covering component testing, composables, Pinia store setup, async components, and common pitfalls like race conditions and snapshot test false positives. Use this to avoid brittle tests and correctly test lifecycle hooks, injections, and end-to-end flows in Vue projects.

Generated from the current SKILL.md.

Does this skill cover both unit and end-to-end testing?
Yes. It covers unit testing with Vitest and Vue Test Utils for components and composables, plus Playwright for E2E testing.
What testing runner does this skill recommend?
Vitest is the recommended unit testing framework for Vue 3 projects.
Does this cover testing Pinia stores?
Yes. The skill includes guidance on setting up Pinia store injection in tests to avoid 'Symbol(pinia) not found' errors.
Can I use this skill to test async components and Suspense?
Yes. The skill covers testing async setup, defineAsyncComponent, and Suspense boundaries.
Does this address flaky tests and race conditions?
Yes. The skill includes patterns for handling async/await and promise flushing to prevent intermittent test failures.

Generated from the current SKILL.md. These answers refresh after source changes.