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.

referenceasync-component-testing.md

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

Use flushPromises for Testing Async Components

Impact: HIGH - When testing async components created with defineAsyncComponent, you must use await flushPromises() to ensure the component has loaded before making assertions. Vue updates asynchronously, so tests that don't account for this will make assertions before the component has rendered.

Task Checklist

  • Use async/await in test functions for async components
  • Call await flushPromises() after mounting async components
  • Test loading states by making assertions before flushPromises()
  • Test error states using rejected promises in defineAsyncComponent
  • Use trigger() with await as it returns a Promise

Incorrect:

import { mount } from '@vue/test-utils'
import { defineAsyncComponent } from 'vue'

const AsyncWidget = defineAsyncComponent(() =>
  import('./Widget.vue')
)

test('renders async component', () => {
  const wrapper = mount(AsyncWidget)

  // FAILS: Component hasn't loaded yet
  expect(wrapper.text()).toContain('Widget Content')
})

Correct:

import { mount, flushPromises } from '@vue/test-utils'
import { defineAsyncComponent, nextTick } from 'vue'

const AsyncWidget = defineAsyncComponent(() =>
  import('./Widget.vue')
)

test('renders async component', async () => {
  const wrapper = mount(AsyncWidget)

  // Wait for async component to load
  await flushPromises()

  expect(wrapper.text()).toContain('Widget Content')
})

test('shows loading state initially', async () => {
  const AsyncWithLoading = defineAsyncComponent({
    loader: () => import('./Widget.vue'),
    loadingComponent: { template: '<div>Loading...</div>' },
    delay: 0
  })

  const wrapper = mount(AsyncWithLoading)

  // Check loading state immediately
  expect(wrapper.text()).toContain('Loading...')

  // Wait for component to load
  await flushPromises()

  // Check final state
  expect(wrapper.text()).toContain('Widget Content')
})

Testing with Suspense

import { mount, flushPromises } from '@vue/test-utils'
import { Suspense, defineAsyncComponent, h } from 'vue'

const AsyncWidget = defineAsyncComponent(() =>
  import('./Widget.vue')
)

test('renders async component with Suspense', async () => {
  const wrapper = mount({
    components: { AsyncWidget },
    template: `
      <Suspense>
        <AsyncWidget />
        <template #fallback>
          <div>Loading...</div>
        </template>
      </Suspense>
    `
  })

  // Initially shows fallback
  expect(wrapper.text()).toContain('Loading...')

  // Wait for async resolution
  await flushPromises()

  // Now shows actual content
  expect(wrapper.text()).toContain('Widget Content')
})

Testing Error States

import { mount, flushPromises } from '@vue/test-utils'
import { defineAsyncComponent } from 'vue'

test('shows error component on load failure', async () => {
  const AsyncWithError = defineAsyncComponent({
    loader: () => Promise.reject(new Error('Failed to load')),
    errorComponent: { template: '<div>Error loading component</div>' }
  })

  const wrapper = mount(AsyncWithError)

  await flushPromises()

  expect(wrapper.text()).toContain('Error loading component')
})

Utilities Reference

Utility Purpose
await flushPromises() Resolves all pending promises
await nextTick() Waits for Vue's next DOM update cycle
await wrapper.trigger('click') Triggers event and waits for update

Dynamic Import Handling

Note: Dynamic imports (import('./File.vue')) may require additional handling beyond flushPromises() in test environments. Test runners like Vitest handle module resolution differently than runtime bundlers, which can cause timing issues with dynamic imports. If flushPromises() alone doesn't resolve the component, consider:

  • Mocking the dynamic import to return the component synchronously
  • Using multiple await flushPromises() calls in sequence
  • Wrapping assertions in waitFor() or retry utilities
  • Configuring your test runner's module resolution settings
// If flushPromises() isn't sufficient, mock the import
vi.mock('./Widget.vue', () => ({
  default: { template: '<div>Widget Content</div>' }
}))

// Or use multiple flush calls for nested async operations
await flushPromises()
await flushPromises()

References

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.