vitest-testing

Vitest testing framework for unit, component, and integration tests. Covers test structure (describe/it/test.each), assertions with expect, lifecycle hooks, mocking (vi.fn/vi.mock/vi.spyOn), React Testing Library patterns, hook testing with renderHook, user-event interactions, async utilities, configuration, workspace setup, coverage, and advanced patterns like in-source testing and concurrent execution. Also covers CLI commands, test filtering, tags, sharding, fixtures with test.extend, and fixture scoping. Use when writing unit tests, component tests, integration tests, or testing React hooks. Use for test configuration, mocking modules, testing async behavior, snapshot testing, or setting up test coverage.

Safety Notice

This listing is imported from skills.sh public index metadata. Review upstream SKILL.md and repository scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "vitest-testing" with this command: npx skills add oakoss/agent-skills/oakoss-agent-skills-vitest-testing

Vitest Testing

Overview

Vitest is a Vite-native unit testing framework that shares the same configuration and plugin ecosystem. Built for speed with native ESM support, hot module replacement for tests, and parallel execution.

When to use: Unit tests, component tests, integration tests, hook tests, in-source tests. Testing React components with React Testing Library. Testing TanStack Query/Router/Form patterns.

When NOT to use: End-to-end testing (use Playwright), visual regression testing (use Percy/Chromatic), load testing (use k6).

Quick Reference

PatternAPIKey Points
Test structuredescribe('suite', () => {})Organize related tests
Single testtest('behavior', () => {}) or it()Both are aliases
Parameterized teststest.each([...])('name', (arg) => {})Run same test with different inputs
Concurrent teststest.concurrent('name', async () => {})Run tests in parallel
Skip testtest.skip('name', () => {}) or skipIf(cond)Conditionally skip tests
Only testtest.only('name', () => {})Run specific test for debugging
Assertionsexpect(value).toBe(expected)Compare primitive values
Deep equalityexpect(obj).toEqual(expected)Compare objects/arrays
Async assertionsawait expect(promise).resolves.toBe(value)Test promise resolution
Before each testbeforeEach(() => {})Setup before each test
After each testafterEach(() => {})Cleanup after each test
Mock functionvi.fn()Create spy function
Mock modulevi.mock('./module')Replace entire module
Spy on methodvi.spyOn(obj, 'method')Track calls to existing method
Clear mocksvi.clearAllMocks()Clear call history
Fake timersvi.useFakeTimers()Control setTimeout/setInterval
Render componentrender(<Component />)Mount React component for testing
Query by rolescreen.getByRole('button')Find elements by accessibility role
User interactionawait user.click(element)Simulate user events
Wait for changeawait waitFor(() => expect(...))Wait for async changes
Find async elementawait screen.findByText('text')Query + wait combined
Render hookrenderHook(() => useHook())Test custom hooks
Update hook propsrerender(newProps)Re-render hook with new props
Snapshotexpect(value).toMatchSnapshot()Compare against saved snapshot
Inline snapshotexpect(value).toMatchInlineSnapshot()Snapshot stored in test file
CLI run oncevitest runSingle run, no watch
Run changed testsvitest --changedTests affected by git changes
Filter by namevitest -t "pattern"Grep test names
Soft assertionsexpect.soft(value).toBe(x)Continue on failure, collect all
Poll assertionsawait expect.poll(() => val).toBe(x)Retry until passing
Test fixturesconst test = base.extend<F>({...})Reusable setup via test.extend
Hoisted mocksvi.hoisted(() => ({ fn: vi.fn() }))Variables for vi.mock factory
Shard testsvitest --shard 1/3Split across CI workers
Tagstest('name', { tags: ['slow'] }, ...)Filter with --tags-filter
Stub globalsvi.stubGlobal('fetch', vi.fn())Replace global objects cleanly

Common Mistakes

MistakeCorrect Pattern
Using getBy for async contentUse findBy or waitFor for async
Testing implementation detailsTest behavior and public API
Using getByTestId as first choicePrefer getByRole, getByLabelText, getByText
Missing userEvent.setup()Always call const user = userEvent.setup() first
Shared state between testsUse beforeEach to reset or create fresh instances
Not cleaning up mocksUse vi.clearAllMocks() in afterEach
Mocking too muchOnly mock external dependencies and APIs
Not disabling retries in testsSet retry: false for TanStack Query tests
Immediate assertions on asyncUse await waitFor() or findBy queries
Creating QueryClient in renderCreate once in wrapper or use useState
Testing library codeTrust the library, test your usage
Not awaiting user eventsAll user.* methods return promises
Using act manuallyuserEvent and Testing Library handle this
Inline select without memoizationExtract to stable function for TanStack Query
Variables in vi.mock factoryUse vi.hoisted() to declare mock variables
Single expect for multiple checksUse expect.soft() to collect all failures
setTimeout in tests for async waitsUse expect.poll() or vi.waitFor()
Manual beforeEach for reusable setupUse test.extend fixtures for composable setup

Delegation

  • Test discovery: For finding untested code paths, use Explore agent
  • Coverage analysis: For full coverage review, use Task agent
  • E2E testing: If playwright skill is available, delegate E2E testing to it
  • Code review: After writing tests, delegate to code-reviewer agent

References

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

Coding

github-cli

No summary provided by upstream source.

Repository SourceNeeds Review
Coding

tanstack-cli

No summary provided by upstream source.

Repository SourceNeeds Review
Coding

typescript-patterns

No summary provided by upstream source.

Repository SourceNeeds Review
Coding

tanstack-devtools

No summary provided by upstream source.

Repository SourceNeeds Review