ferroxlabs/wayland/vue-testing-patterns

Claude Code and agent skill by ferroxlabs/wayland

Trust tier 3
  • community
  • ext:[{"type":"hook","description":"Pre/post lifecycle hooks"},{"type":"plugin","description":"Custom plugin integration"}]
Source check pending

Checking that the SKILL.md file is still in the repository.

Guides expert-level vue testing patterns implementation: javascript and testing decision frameworks, production-ready patterns, and concrete templates for vue testing patterns workflows. Use when the user asks about vue testing patterns, vue testing patterns configuration, or javascript best practices for vue projects. Do NOT use when the user needs a different web development capability -- check sibling skills in the web development subcategory.

Install

npx vskill@latest install ferroxlabs/wayland/vue-testing-patterns

Semi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard

SKILL.md

The same SKILL.md was published earlier as ferroxlabs/wayland/vue-testing-patterns.

Vue Testing Patterns

When to Use

Use this skill when:

  • User is writing tests for Vue 3 components using Vitest, Jest, or Vue Test Utils and needs guidance on structure, patterns, or common pitfalls
  • User wants to test Pinia stores, composables, or reactive logic in isolation without mounting full components
  • User is setting up a testing strategy for a Vue project and needs to decide between unit, integration, and end-to-end test coverage boundaries
  • User is migrating tests from Vue 2 / Vue Test Utils v1 / Vue CLI Jest to Vue 3 / Vue Test Utils v2 / Vitest
  • User has flaky tests, slow test suites, or tests that break on internal refactors rather than behavioral changes
  • User wants to test async operations, watchers, lifecycle hooks, or complex user interactions in Vue components
  • User is implementing TDD for a Vue feature and needs concrete patterns for writing tests before components

Do NOT use this skill when:

  • User needs help setting up end-to-end testing with Cypress or Playwright -- use the e2e-testing skill instead
  • User needs help with Vue 3 component architecture or composition API design -- use the vue-composition-api skill
  • User needs TypeScript configuration for a Vue project -- use the vue-typescript-setup skill
  • User is asking about React Testing Library or Angular testing -- those are different framework skills
  • User needs CI/CD pipeline configuration that includes testing -- use the ci-cd-pipeline skill
  • User needs performance profiling of Vue applications -- use the vue-performance-optimization skill

Process

1. Identify What Needs to Be Tested and at What Level

Before writing a single test, determine the correct testing level for the code under test.

  • Unit tests target a single composable, utility function, or simple presentational component in isolation. These run in milliseconds and should form the bulk of your suite (70%+ by count).
  • Component integration tests mount one component with real child components and real Pinia stores, testing the rendered output and user interactions. These are the highest-value tests for Vue -- they test behavior without coupling to implementation.
  • Shallow render tests are rarely the right choice. Use shallowMount only for components with expensive or side-effectful children that cannot be stubbed cleanly. Prefer mount for integration value.
  • Draw the test boundary at the public contract: props in, emits out, slots rendered, DOM mutations, store state changes. Never test internal ref values, internal method calls, or private composable internals.
  • Apply the 70/20/10 heuristic: 70% unit tests on composables and utilities, 20% component integration tests, 10% E2E tests on critical paths.
2. Configure the Test Environment Correctly

A misconfigured test environment causes more wasted time than poor test design. Get this right first.

  • Use Vitest as the default for Vue 3 projects. It shares Vite config, supports HMR in watch mode, and has first-class Vue Plugin support. Use Jest only if the project is already committed to it.
  • Set environment: 'jsdom' or environment: 'happy-dom' in vitest.config.ts. happy-dom is 2-5x faster but has less complete DOM API coverage. Use happy-dom unless you hit missing API errors.
  • Install @vue/test-utils@^2, @pinia/testing, and either vitest or jest + @vue/vue3-jest.
  • Configure global plugins in vitest.config.ts under test.globals so you don't repeat them per file:
typescript
// vitest.config.ts
import { defineConfig } from 'vitest/config'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
test: {
environment: 'happy-dom',
globals: true,
setupFiles: ['./src/test/setup.ts'],
},
})
  • Create a setup.ts file that installs global plugins (e.g., i18n, router mocks, custom directives) once rather than in every test file.
  • Set server.deps.inline: ['vuetify'] (or your UI library) if using SSR-incompatible dependencies that fail module resolution in Vitest.
3. Structure Tests Using the Arrange-Act-Assert Pattern with Vue Semantics

Vue testing has specific timing requirements that break naive AAA implementations.

  • Always await nextTick() after triggering reactive state changes before asserting on the DOM. Failure to do this is the single most common source of false-passing tests.
  • Use await wrapper.trigger('click') -- Vue Test Utils triggers return a promise that resolves after the DOM has updated. Always await it.
  • Use flushPromises() from @vue/test-utils after async operations (API calls, async watchers, onMounted async work) before asserting. This drains the microtask queue completely.
  • Structure test files with describe blocks matching component name, then nested describe blocks for logical groups (rendering, user interactions, emits, edge cases):
typescript
describe('UserCard', () => {
describe('rendering', () => { ... })
describe('user interactions', () => { ... })
describe('emitted events', () => { ... })
})
  • Place beforeEach factory functions at the top of each describe block. Create a createWrapper factory function instead of repeating mount calls -- this makes adding props to specific tests trivial without breaking others.
4. Mount Components Correctly with Proper Plugin Context

A component mounted without its expected dependencies will fail in ways that obscure the real test intent.

  • Use the global mounting option to provide plugins per test or per file:
typescript
const wrapper = mount(UserCard, {
global: {
plugins: [createTestingPinia({ initialState: { user: { name: 'Alice' } } })],
stubs: { RouterLink: true },
mocks: { $t: (key: string) => key },
},
props: { userId: '42' },
})
  • Use createTestingPinia from @pinia/testing instead of the real Pinia. It makes all store actions spies by default, preventing real network calls.
  • Stub RouterLink and RouterView with { RouterLink: true, RouterView: true } unless you are specifically testing routing behavior. Real router setup in unit tests adds noise.
  • For components that use provide/inject, use the global.provide mounting option:
typescript
const wrapper = mount(ThemeConsumer, {
global: { provide: { theme: 'dark' } },
})
  • For slots, use the slots mounting option with template strings or render functions. Test that the correct slot content is rendered, not the slot mechanism itself.
5. Test Composables in Isolation Using withSetup

Composables are the most testable unit in Vue 3. Test them directly without mounting a component.

  • For composables that require a Vue instance context (lifecycle hooks, provide/inject, getCurrentInstance), wrap them in a minimal component using a withSetup helper:
typescript
// test/helpers/withSetup.ts
import { createApp } from 'vue'
export function withSetup<T>(composable: () => T): [T, ReturnType<typeof createApp>] {
let result: T
const app = createApp({
setup() {
result = composable()
return () => {}
},
})
app.mount(document.createElement('div'))
return [result!, app]
}
  • Use this pattern to test lifecycle hooks: call app.unmount() to trigger onUnmounted handlers and assert cleanup occurred.
  • For pure composables (no lifecycle hooks, no provide/inject), call them directly in tests inside a withReactivity wrapper or simply inline -- Vitest runs in the same Vue reactive context.
  • Test the return value of composables, not their internals. If useCounter returns { count, increment, decrement }, test those values and functions. Never destructure reactive refs before returning them (they lose reactivity), and verify your composable doesn't do this either.
  • Mock fetch or axios at the module level using vi.mock or jest.mock before testing composables that make network requests.
6. Test Pinia Stores Directly

Pinia stores are plain objects with reactive state -- test them like you would test a class.

  • Import the store definition and call it directly inside a setActivePinia(createPinia()) context:
typescript
import { setActivePinia, createPinia } from 'pinia'
import { useCartStore } from '@/stores/cart'
beforeEach(() => {
setActivePinia(createPinia())
})
it('adds item to cart', () => {
const cart = useCartStore()
cart.addItem({ id: '1', name: 'Widget', price: 9.99 })
expect(cart.items).toHaveLength(1)
expect(cart.total).toBe(9.99)
})
  • For stores with async actions that call APIs, mock the API module using vi.mock at the top of the test file, then verify the store state after the action resolves.
  • Test getters independently of actions. If a getter discountedTotal depends on total and a discount property, set state directly and assert the getter's output without going through actions.
  • Use $patch to set up complex initial state for getter tests rather than calling multiple actions in sequence -- it's faster and more direct.
  • For stores that call other stores, use createTestingPinia with initialState to set up multi-store state in one call.
7. Assert on Behavior, Not Implementation

The most important discipline in Vue testing is choosing what to assert.

  • Assert on what the user sees: expect(wrapper.text()).toContain('Welcome, Alice') not expect(wrapper.vm.displayName).toBe('Welcome, Alice').
  • Assert on DOM structure only when it carries semantic meaning: expect(wrapper.find('[data-testid="error-message"]').exists()).toBe(true) is better than expect(wrapper.find('.error-text').exists()).toBe(true).
  • Use data-testid attributes on elements that tests need to find. Never use CSS classes or element tags as test selectors -- they change for styling reasons and break tests unnecessarily.
  • Assert on emitted events using wrapper.emitted():
typescript
await wrapper.find('[data-testid="submit-btn"]').trigger('click')
expect(wrapper.emitted('form-submit')).toHaveLength(1)
expect(wrapper.emitted('form-submit')![0]).toEqual([{ name: 'Alice', email: 'alice@example.com' }])
  • Avoid wrapper.vm access in assertions except for debugging. If you find yourself asserting wrapper.vm.someInternalState, your test is too tightly coupled to implementation.
  • For component props validation tests, assert that the rendered output reflects the prop value, not that Vue's prop validation system ran.
8. Handle Async, Timers, and Network Calls

Async is the leading cause of flaky Vue tests. Follow these patterns consistently.

  • Mock setTimeout/setInterval/Date.now() using vi.useFakeTimers() in beforeEach and vi.useRealTimers() in afterEach. Advance time with vi.advanceTimersByTime(ms) or vi.runAllTimers().
  • For debounced or throttled inputs, use fake timers and advance by the debounce duration (e.g., 300ms) before asserting:
typescript
vi.useFakeTimers()
await wrapper.find('input').trigger('input')
vi.advanceTimersByTime(300)
await nextTick()
expect(mockSearchFn).toHaveBeenCalledWith('query')
  • Mock fetch using vi.fn() or use msw (Mock Service Worker) for component tests that involve multiple API calls. MSW is preferable for integration tests because it intercepts at the network level and avoids brittle mock setup.
  • Always clean up mocks in afterEach using vi.restoreAllMocks() or vi.clearAllMocks(). Configure this globally in setup.ts with afterEach(() => vi.clearAllMocks()).
  • For components using onMounted async initialization, await flushPromises() immediately after mounting before making assertions.

Output Format

When providing Vue testing guidance, use this structure:

## Test Strategy for [Component/Feature Name]
### Testing Level
- Primary: [unit / integration / E2E]
- Rationale: [one sentence explaining why]
### Test File Structure
[filepath and filename]

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 98 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
5

Not refreshed yet.

Extension points

  • hookPre/post lifecycle hooks
  • pluginCustom plugin integration

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/ferroxlabs/wayland/vue-testing-patterns/badge)](https://verified-skill.com/skills/ferroxlabs/wayland/vue-testing-patterns)

Something wrong with this skill or its page? Tell us.