vitest-testing
Skill4 starsChanged 4 months agoMITView on GitHub
Vitest — fast unit testing with Testing Library integration and test pyramid strategy
- Installs packages
1 other project uses a version of this.
Adopted by
Most recently taken up by
- yutakobayashidev/skillstheir own version, first seen Jun 1, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- yutakobayashidev/skills★ 1same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository162 other files it gives its agents.
- agents/AGENTS.mdAGENTS.md
- skills/compound-engineering/AGENTS.mdAGENTS.md
- skills/trailofbits-security/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- examples/CLAUDE.mdCLAUDE.md
- skills/compound-engineering/CLAUDE.mdCLAUDE.md
- skills/trailofbits-security/CLAUDE.mdCLAUDE.md
- app-store-reviewSkill
- advanced-javascriptSkill
- ai-native-uiSkill
- anime-jsSkill
- app-l100Skill
- barba-jsSkill
- brand-guidelinesSkill
- cinematic-web-engineSkill
- codebase-knowledge-graphSkill
- crossplatform-monorepoSkill
- css-first-uiSkill
- design-auditSkill
- design-critiqueSkill
- dev-cycleSkill
- device-hardware-bridgeSkill
- discovery-docSkill
- docxSkill
- edge-intelligenceSkill
- graph-aware-reviewSkill
- linkedin-posterSkill
- local-first-architectureSkill
- modern-build-pipelineSkill
- motion-nativeSkill
- nano-bananaSkill
- playwrightSkill
- pptxSkill
- project-initSkill
- remotionSkill
- sensory-nativeSkill
- spline-3dSkill
- streaming-cacheSkill
- tanstack-ecosystemSkill
- design-taste-frontendSkill
- tauri-desktopSkill
- threejsSkill
- transition-nativeSkill
- ui-design-stackSkill
- visual-nativeSkill
- web-l100Skill
- web-platform-apisSkill
- xlsxSkill
- better-authSkill
- claude-real-videoSkill
- clone-websiteSkill
- css-keyframe-animationsSkill
- design-checkSkill
- design-dnaSkill
- design-polishSkill
- drizzle-neonSkill
- fastlaneSkill
- angular-architectSkill
- api-designerSkill
- architecture-designerSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
2 rules. About 0 are common, 0 are distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 284
Use --pool=threads (default) for speed, --pool=forks for isolation
- Very specific: line 287
Avoid beforeAll database seeding — use per-test factories instead
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Vitest Testing
When to Use This Skill
Apply when writing tests for any Vite-based or modern JS/TS project. Vitest is the 2026 default (6x faster than Jest, native ESM, shared Vite config). Test pyramid: Vitest for unit + component, Playwright for E2E. Auto-activate on keywords: vitest, test, describe, it, expect, mock, coverage.
Related skills: Playwright for E2E browser testing — via the anthropic-skills:playwright-cli skill or the Claude Browser / MCP_DOCKER browser tools (the old SK-009 Playwright skill is retired).
Installation
npm install -D vitest @testing-library/react @testing-library/jest-dom @testing-library/user-event jsdomConfiguration
// vitest.config.ts (or in vite.config.ts)
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
globals: true, // no import { describe, it, expect }
environment: 'jsdom', // 'node' for server code
setupFiles: './src/test/setup.ts',
include: ['**/*.{test,spec}.{ts,tsx}'],
coverage: {
provider: 'v8', // or 'istanbul'
reporter: ['text', 'html', 'lcov'],
thresholds: { lines: 80, branches: 80, functions: 80 },
},
css: true, // process CSS imports
},
});Setup file:
// src/test/setup.ts
import '@testing-library/jest-dom/vitest';Basic Test Structure (Arrange-Act-Assert)
import { describe, it, expect, beforeEach } from 'vitest';
describe('calculateTotal', () => {
it('returns sum of item prices', () => {
// Arrange
const items = [{ price: 10 }, { price: 20 }, { price: 30 }];
// Act
const total = calculateTotal(items);
// Assert
expect(total).toBe(60);
});
it('returns 0 for empty array', () => {
expect(calculateTotal([])).toBe(0);
});
it('throws on negative prices', () => {
expect(() => calculateTotal([{ price: -5 }])).toThrow('Invalid price');
});
});Component Testing with Testing Library
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi } from 'vitest';
import { Counter } from './Counter';
describe('Counter', () => {
it('increments count on button click', async () => {
const user = userEvent.setup();
render(<Counter initialCount={0} />);
expect(screen.getByText('Count: 0')).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: /increment/i }));
expect(screen.getByText('Count: 1')).toBeInTheDocument();
});
it('calls onChange callback with new value', async () => {
const onChange = vi.fn();
const user = userEvent.setup();
render(<Counter initialCount={5} onChange={onChange} />);
await user.click(screen.getByRole('button', { name: /increment/i }));
expect(onChange).toHaveBeenCalledWith(6);
});
});Mocking
Module mocks:
import { vi, describe, it, expect } from 'vitest';
// Mock entire module
vi.mock('./api', () => ({
fetchUser: vi.fn(),
}));
import { fetchUser } from './api';
describe('UserService', () => {
it('fetches and transforms user', async () => {
vi.mocked(fetchUser).mockResolvedValue({ id: '1', name: 'Alice' });
const result = await getUser('1');
expect(result.displayName).toBe('Alice');
});
});Spy on methods:
const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
// ... test code that should log error ...
expect(spy).toHaveBeenCalledWith(expect.stringContaining('failed'));
spy.mockRestore();Mock timers:
import { vi, beforeEach, afterEach } from 'vitest';
beforeEach(() => { vi.useFakeTimers(); });
afterEach(() => { vi.useRealTimers(); });
it('debounces input', async () => {
const callback = vi.fn();
const debounced = debounce(callback, 300);
debounced('hello');
expect(callback).not.toHaveBeenCalled();
vi.advanceTimersByTime(300);
expect(callback).toHaveBeenCalledWith('hello');
});Mock fetch:
import { vi } from 'vitest';
const mockFetch = vi.fn();
global.fetch = mockFetch;
mockFetch.mockResolvedValueOnce({
ok: true,
json: () => Promise.resolve({ id: '1', name: 'Alice' }),
});Async Testing
it('resolves with user data', async () => {
const user = await fetchUser('1');
expect(user).toEqual({ id: '1', name: 'Alice' });
});
it('rejects on not found', async () => {
await expect(fetchUser('999')).rejects.toThrow('Not found');
});
// Wait for condition
import { waitFor } from '@testing-library/react';
await waitFor(() => {
expect(screen.getByText('Loaded')).toBeInTheDocument();
});Testing Hooks
import { renderHook, act } from '@testing-library/react';
it('increments counter', () => {
const { result } = renderHook(() => useCounter(0));
expect(result.current.count).toBe(0);
act(() => result.current.increment());
expect(result.current.count).toBe(1);
});Testing with TanStack Query
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
function createWrapper() {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
return ({ children }: { children: React.ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
}
it('displays user data', async () => {
mockFetch.mockResolvedValueOnce({ ok: true, json: () => ({ name: 'Alice' }) });
render(<UserProfile userId="1" />, { wrapper: createWrapper() });
expect(await screen.findByText('Alice')).toBeInTheDocument();
});Snapshot Testing
it('matches snapshot', () => {
const { container } = render(<Button variant="primary">Click</Button>);
expect(container.firstChild).toMatchSnapshot();
});
// Inline snapshot (preferred — visible in test file)
it('serializes config', () => {
expect(getConfig()).toMatchInlineSnapshot(`
{
"debug": false,
"port": 3000,
}
`);
});Coverage
vitest run --coverage # run with coverage
vitest --coverage --watch # watch mode with coverageTest Pyramid Strategy
/ E2E \ Playwright — critical user flows (5-10 tests)
/----------\
/ Component \ Vitest + Testing Library — UI behavior (many)
/--------------\
/ Unit Tests \ Vitest — pure functions, utils, hooks (most)
/--------------------\Rules:
- Unit tests: pure functions, utilities, hooks, reducers. Fast, isolated.
- Component tests: render + interact + assert. Mock external deps, not internal state.
- E2E tests: critical user paths only (auth flow, checkout, data CRUD). Slow, flaky risk.
- Test behavior, not implementation. Query by role/text, not class/id.
- One assertion cluster per test. Multiple related expects OK, but one logical check.
- Co-locate tests:
foo.ts→foo.test.tsin same directory.
CLI Commands
vitest # watch mode (default)
vitest run # single run (CI)
vitest run src/utils # run tests in specific directory
vitest -t "calculates" # run tests matching name
vitest --reporter=verbose # detailed output
vitest bench # run benchmarksPerformance Tips
- Vitest runs tests in worker threads — parallel by default
- Use
--pool=threads(default) for speed,--pool=forksfor isolation --sequence.concurrentto run tests within a file concurrentlyvi.mockis hoisted automatically — no need for manual hoisting- Avoid
beforeAlldatabase seeding — use per-test factories instead
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

