jest-vitest
Use this skill when writing unit tests with Jest or Vitest, implementing mocking strategies, configuring test runners, or improving test coverage. Triggers on Jest, Vitest, describe/it/expect, mocking, vi.fn, jest.fn, snapshot testing, test coverage, and any task requiring JavaScript/TypeScript unit testing.
engineering jestvitestunit-testingmockingcoveragetestingWhat is jest-vitest?
Use this skill when writing unit tests with Jest or Vitest, implementing mocking strategies, configuring test runners, or improving test coverage. Triggers on Jest, Vitest, describe/it/expect, mocking, vi.fn, jest.fn, snapshot testing, test coverage, and any task requiring JavaScript/TypeScript unit testing.
jest-vitest
jest-vitest is a production-ready AI agent skill for claude-code, gemini-cli, openai-codex. Writing unit tests with Jest or Vitest, implementing mocking strategies, configuring test runners, or improving test coverage.
Quick Facts
| Field | Value |
|---|---|
| Category | engineering |
| Version | 0.1.0 |
| Platforms | claude-code, gemini-cli, openai-codex |
| License | MIT |
How to Install
- Make sure you have Node.js installed on your machine.
- Run the following command in your terminal:
npx skills add AbsolutelySkilled/AbsolutelySkilled --skill jest-vitest- The jest-vitest skill is now available in your AI coding agent (Claude Code, Gemini CLI, OpenAI Codex, etc.).
Overview
Jest and Vitest are the dominant unit testing frameworks for JavaScript and
TypeScript. Jest is the battle-tested choice bundled with Create React App and
widely adopted across Node.js ecosystems. Vitest is the modern successor - it
reuses Vite's transform pipeline, offers a compatible API, and is significantly
faster for projects already on Vite. Both share the same describe/it/expect
vocabulary, making knowledge transferable. This skill covers writing
well-structured tests, mocking strategies, async patterns, snapshot testing,
React component testing, and coverage analysis.
Tags
jest vitest unit-testing mocking coverage testing
Platforms
- claude-code
- gemini-cli
- openai-codex
Related Skills
Pair jest-vitest with these complementary skills:
Frequently Asked Questions
What is jest-vitest?
Use this skill when writing unit tests with Jest or Vitest, implementing mocking strategies, configuring test runners, or improving test coverage. Triggers on Jest, Vitest, describe/it/expect, mocking, vi.fn, jest.fn, snapshot testing, test coverage, and any task requiring JavaScript/TypeScript unit testing.
How do I install jest-vitest?
Run npx skills add AbsolutelySkilled/AbsolutelySkilled --skill jest-vitest in your terminal. The skill will be immediately available in your AI coding agent.
What AI agents support jest-vitest?
This skill works with claude-code, gemini-cli, openai-codex. Install it once and use it across any supported AI coding agent.
Maintainers
Generated from AbsolutelySkilled
SKILL.md
Jest / Vitest
Jest and Vitest are the dominant unit testing frameworks for JavaScript and
TypeScript. Jest is the battle-tested choice bundled with Create React App and
widely adopted across Node.js ecosystems. Vitest is the modern successor - it
reuses Vite's transform pipeline, offers a compatible API, and is significantly
faster for projects already on Vite. Both share the same describe/it/expect
vocabulary, making knowledge transferable. This skill covers writing
well-structured tests, mocking strategies, async patterns, snapshot testing,
React component testing, and coverage analysis.
When to use this skill
Trigger this skill when the user:
- Asks to write, review, or improve unit tests in JavaScript or TypeScript
- Mentions Jest, Vitest,
describe,it,test,expect, orbeforeEach - Needs to mock a module, function, or dependency (
vi.fn,jest.fn,vi.mock) - Asks about snapshot testing or updating snapshots
- Wants to configure a test runner for a new or existing project
- Needs to test React (or other UI) components with
@testing-library - Asks about test coverage - thresholds, gaps, or measuring it
- Is migrating a test suite from Jest to Vitest
Do NOT trigger this skill for:
- End-to-end or browser automation testing (use Playwright / Cypress skills instead)
- Static analysis or linting - these are not tests
Key principles
Test behavior, not implementation - Tests should verify what a unit does from the outside, not how it does it internally. Tests that reach into private state or assert on internal call sequences break during refactoring even when behavior is unchanged.
Arrange-Act-Assert - Every test has three clear sections: set up the preconditions, perform the action under test, then assert the outcome. Keep each section small. Long Arrange sections signal the API is too complex.
One assertion concept per test - A test should fail for exactly one reason. Multiple
expectcalls are fine when they all verify the same behavioral concept. Tests that verify two unrelated concepts hide which behavior broke.Mock at boundaries, not internals - Mock I/O and external services (HTTP clients, databases, file system, timers) at their entry point. Do not mock internal helper functions within the same module - that tests the wiring, not the behavior.
Fast tests run more often - A suite that completes in under 10 seconds gets run on every save. One that takes 2 minutes gets run before commits only. Keep unit tests in-memory: no real network, no real filesystem, no real clocks.
Core concepts
Test lifecycle
beforeAll → runs once before all tests in a describe block
beforeEach → runs before each individual test
afterEach → runs after each individual test (cleanup)
afterAll → runs once after all tests in a describe blockPrefer beforeEach / afterEach over beforeAll / afterAll. Shared state
across tests causes order-dependent failures that are painful to debug.
Matchers
| Matcher | Use for |
|---|---|
toBe(value) |
Strict equality (===) for primitives |
toEqual(value) |
Deep equality for objects and arrays |
toStrictEqual(value) |
Deep equality including undefined properties and class instances |
toMatchObject(partial) |
Object contains at least these keys/values |
toContain(item) |
Array contains item, string contains substring |
toThrow(error?) |
Function throws (wrap in () => fn()) |
toHaveBeenCalledWith(...args) |
Mock was called with specific arguments |
toHaveBeenCalledTimes(n) |
Mock call count |
resolves / rejects |
Chain on Promises: await expect(p).resolves.toBe(x) |
Mock types
| Type | API | Purpose |
|---|---|---|
| Function mock | vi.fn() / jest.fn() |
Replaces a function, records calls |
| Spy | vi.spyOn(obj, 'method') |
Wraps an existing method, records calls, can restore |
| Module mock | vi.mock('module') / jest.mock('module') |
Replaces an entire module's exports |
Snapshot testing
Snapshots serialize a value to a .snap file on first run, then assert the
value matches that serialization on subsequent runs. Use snapshots for stable,
complex output (serialized data structures, CLI output). Avoid snapshots for
UI components rendered to HTML - they become noisy and get blindly updated.
Update stale snapshots intentionally with --updateSnapshot (-u) after
reviewing the diff.
Coverage metrics
| Metric | What it measures |
|---|---|
| Statements | Percentage of executable statements run |
| Branches | Percentage of if/else/ternary paths taken |
| Functions | Percentage of functions called at least once |
| Lines | Percentage of source lines executed |
Branch coverage is the most meaningful metric. A function with 100% statement
coverage but 60% branch coverage has untested if paths that can fail in
production. Aim for 80%+ branch coverage on business logic.
Common tasks
Write well-structured tests with AAA
// src/cart.test.ts
import { describe, it, expect, beforeEach } from 'vitest';
import { Cart } from './cart';
describe('Cart', () => {
let cart: Cart;
beforeEach(() => {
// Arrange - fresh cart for each test, no shared state
cart = new Cart();
});
it('starts empty', () => {
// Assert only - trivial arrange already done
expect(cart.itemCount()).toBe(0);
expect(cart.total()).toBe(0);
});
it('adds items and updates total', () => {
// Act
cart.add({ id: '1', name: 'Widget', price: 9.99, quantity: 2 });
// Assert
expect(cart.itemCount()).toBe(2);
expect(cart.total()).toBeCloseTo(19.98);
});
it('throws when adding an item with zero quantity', () => {
expect(() =>
cart.add({ id: '1', name: 'Widget', price: 9.99, quantity: 0 })
).toThrow('Quantity must be positive');
});
});Mock modules and dependencies
// src/order-service.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest';
// Module mock hoisted to top of file by Vitest/Jest
vi.mock('./payment-gateway', () => ({
charge: vi.fn(),
}));
vi.mock('./mailer', () => ({
sendConfirmation: vi.fn(),
}));
import { placeOrder } from './order-service';
import { charge } from './payment-gateway';
import { sendConfirmation } from './mailer';
describe('placeOrder', () => {
beforeEach(() => {
vi.resetAllMocks();
});
it('charges the customer and sends a confirmation on success', async () => {
// Arrange
vi.mocked(charge).mockResolvedValue({ success: true, transactionId: 'txn_123' });
const order = { id: 'ord_1', total: 49.99, customer: { email: 'a@b.com' } };
// Act
await placeOrder(order);
// Assert
expect(charge).toHaveBeenCalledWith({ amount: 49.99, orderId: 'ord_1' });
expect(sendConfirmation).toHaveBeenCalledWith('a@b.com', 'ord_1');
});
it('throws OrderFailedError when payment is declined', async () => {
vi.mocked(charge).mockResolvedValue({ success: false, error: 'Insufficient funds' });
const order = { id: 'ord_2', total: 200, customer: { email: 'a@b.com' } };
await expect(placeOrder(order)).rejects.toThrow('OrderFailedError');
expect(sendConfirmation).not.toHaveBeenCalled();
});
});Test async code - promises, timers, and events
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { fetchUser } from './user-api';
// --- Promises ---
it('resolves with user data', async () => {
const user = await fetchUser('user-1');
expect(user).toMatchObject({ id: 'user-1', name: expect.any(String) });
});
it('rejects when user is not found', async () => {
await expect(fetchUser('nonexistent')).rejects.toThrow('User not found');
});
// --- Fake timers (debounce, throttle, setTimeout) ---
describe('debounced search', () => {
beforeEach(() => { vi.useFakeTimers(); });
afterEach(() => { vi.useRealTimers(); });
it('fires callback once after debounce delay', () => {
const callback = vi.fn();
const search = createDebouncedSearch(callback, 300);
search('re');
search('rea');
search('react');
expect(callback).not.toHaveBeenCalled();
vi.advanceTimersByTime(300);
expect(callback).toHaveBeenCalledOnce();
expect(callback).toHaveBeenCalledWith('react');
});
});
// --- Event emitters ---
it('emits "ready" after initialization', () =>
new Promise<void>((resolve) => {
const service = new DataService();
service.on('ready', () => {
expect(service.isReady()).toBe(true);
resolve();
});
service.init();
})
);Snapshot testing done right
import { describe, it, expect } from 'vitest';
import { serializeCartSummary } from './cart-serializer';
describe('serializeCartSummary', () => {
it('produces stable JSON for a standard cart', () => {
const cart = buildCart([
{ sku: 'A1', qty: 2, price: 10 },
{ sku: 'B3', qty: 1, price: 25.5 },
]);
// Snapshot is useful here: the serialization format is complex and
// must remain stable for API consumers.
expect(serializeCartSummary(cart)).toMatchSnapshot();
});
});
// When output changes intentionally, review the diff then run:
// npx vitest --updateSnapshot
// Do NOT blindly run -u without reading the diff first.Configure Vitest for a project
// vitest.config.ts
import { defineConfig } from 'vitest/config';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [react()],
test: {
environment: 'jsdom', // use 'node' for server-side code
globals: true, // avoids importing describe/it/expect in every file
setupFiles: ['./src/test-setup.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'lcov', 'html'],
thresholds: {
branches: 80,
functions: 80,
lines: 80,
statements: 80,
},
exclude: [
'src/**/*.d.ts',
'src/**/index.ts', // barrel files
'src/**/*.stories.tsx', // Storybook
],
},
},
});// src/test-setup.ts
import '@testing-library/jest-dom'; // extends expect with .toBeInTheDocument() etc.
import { afterEach } from 'vitest';
import { cleanup } from '@testing-library/react';
afterEach(() => {
cleanup(); // unmount React trees after each test
});Test React components with testing-library
// src/components/LoginForm.test.tsx
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { LoginForm } from './LoginForm';
describe('LoginForm', () => {
it('submits email and password when the form is valid', async () => {
const user = userEvent.setup();
const onSubmit = vi.fn().mockResolvedValue(undefined);
render(<LoginForm onSubmit={onSubmit} />);
await user.type(screen.getByLabelText(/email/i), 'user@example.com');
await user.type(screen.getByLabelText(/password/i), 'secret123');
await user.click(screen.getByRole('button', { name: /log in/i }));
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledWith({
email: 'user@example.com',
password: 'secret123',
});
});
});
it('shows a validation error when email is empty', async () => {
const user = userEvent.setup();
render(<LoginForm onSubmit={vi.fn()} />);
await user.click(screen.getByRole('button', { name: /log in/i }));
expect(screen.getByText(/email is required/i)).toBeInTheDocument();
});
});Query priority for @testing-library: getByRole > getByLabelText >
getByPlaceholderText > getByText > getByTestId. Prefer role-based queries
because they reflect how assistive technology sees the page.
Measure and improve coverage
# Run tests with coverage
npx vitest run --coverage
# Or with Jest
npx jest --coverage
# View HTML report (Vitest)
open coverage/index.htmlTo find untested branches, look for E (else not taken) and I (if not taken)
markers in the Istanbul HTML report. Focus on:
- Error paths - what happens when a fetch fails, input is invalid, or a service throws
- Guard clauses - early returns and null checks
- Complex conditionals - expressions with multiple
&&/||operators
Anti-patterns
| Anti-pattern | Why it's harmful | What to do instead |
|---|---|---|
| Testing implementation details | Asserts on private state, internal call order, or mocked internals - breaks during refactoring without catching real bugs | Test observable outputs and public API behavior |
| One giant test per function | A single test with 15 assertions hides which scenario failed | One test per behavior: happy path, each error case, each edge case |
| Mocking what you own | Mocking internal helpers inside the module under test leaves the real integration untested | Only mock external boundaries (HTTP, DB, file system, time) |
beforeAll shared mutable state |
Tests pass individually but fail when run in sequence due to mutated shared objects | Use beforeEach to create fresh instances for every test |
| Snapshot-everything | Applying .toMatchSnapshot() to all component output means reviewers never read snapshot diffs and always blindly update |
Use snapshots only for stable, complex serializations - not HTML |
Skipping vi.resetAllMocks() |
Mock return values and call counts bleed between tests causing false positives | Call vi.resetAllMocks() in afterEach or enable clearMocks: true in config |
Gotchas
vi.mock()calls are hoisted but imports are not - order matters - Vitest (and Jest) hoistvi.mock()calls to the top of the file at compile time, but the imported mock values are still assigned at runtime. If you reference a mock return value before callingvi.mocked(fn).mockReturnValue(...), you'll getundefined. Always configure mock return values insidebeforeEachor inside the test body, not at the module scope.jsdomenvironment makes Node-specific APIs silently undefined - If your test config setsenvironment: 'jsdom'but the code under test uses Node APIs likefs,path, orprocess.env, those may behave differently or return undefined without error. Useenvironment: 'node'for server-side code and restrictjsdomto browser/component tests only.Fake timers must be cleaned up or they leak into subsequent tests - Calling
vi.useFakeTimers()in a test withoutvi.useRealTimers()inafterEachmeans every subsequent test in the suite runs with fake timers.setTimeoutin unrelated tests will never fire, producing mysterious timeouts. Always restore real timers in the teardown of any test that uses fake ones.toMatchSnapshot()on React components captures the entire rendered HTML, making every UI change a snapshot failure - Component snapshots become a maintenance burden because every intentional style or markup change requires running--updateSnapshot, and reviewers stop reading the diffs. Use snapshots for stable serialized data structures, not rendered component output.vi.resetAllMocks()vsvi.clearAllMocks()vsvi.restoreAllMocks()are not the same -clearAllMocksclears call history but keeps implementations.resetAllMocksremoves both history and mock implementations.restoreAllMocksalso restores spied-on originals. Using the wrong one leaves either stale call counts or stale mock return values, causing false-positive test passes in later tests.
References
For deep dives, read the relevant file from references/:
references/migration-guide.md- Step-by-step Jest to Vitest migration, API diffs, config changes
References
migration-guide.md
Jest to Vitest Migration Guide
Vitest is API-compatible with Jest for the vast majority of use cases. Most projects can migrate in a few hours. The main work is replacing configuration, swapping the import source for test utilities, and handling a handful of API differences.
Why migrate
| Factor | Jest | Vitest |
|---|---|---|
| Transform pipeline | Babel/ts-jest (separate config) | Reuses Vite config |
| Cold start (large suite) | 3-8 s | 0.3-1 s |
| Watch mode HMR | Full re-run of changed files | Module-level HMR |
| ESM support | Experimental, config-heavy | Native |
| TypeScript | Requires ts-jest or babel-jest |
Built-in, zero config |
| Config file | jest.config.js |
vitest.config.ts |
Migrate when: your project already uses Vite, you want faster feedback loops, or you are tired of maintaining separate Babel/ts-jest config.
Do NOT migrate if: your project does not use Vite and you would need to add it just for testing. The DX gains are smaller if you introduce a full build-tool dependency only for tests.
Step-by-step migration
1. Install Vitest
npm install -D vitest @vitest/coverage-v8
# If using jsdom (React, browser-like tests):
npm install -D jsdom
# If using happy-dom (lighter alternative):
npm install -D happy-dom2. Replace jest.config with vitest.config.ts
// vitest.config.ts (replaces jest.config.js)
import { defineConfig } from 'vitest/config';
// If you already have a vite.config.ts, extend it instead:
// import { mergeConfig } from 'vitest/config';
// import viteConfig from './vite.config';
export default defineConfig({
test: {
globals: true, // enable describe/it/expect globally (matches Jest default)
environment: 'jsdom', // or 'node' or 'happy-dom'
setupFiles: ['./src/test-setup.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'lcov', 'html'],
},
},
});If you have an existing vite.config.ts, merge rather than duplicate:
// vitest.config.ts
import { defineConfig, mergeConfig } from 'vitest/config';
import viteConfig from './vite.config';
export default mergeConfig(viteConfig, defineConfig({
test: {
globals: true,
environment: 'jsdom',
},
}));3. Update package.json scripts
{
"scripts": {
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage"
}
}4. Update imports in test files
Jest injects describe, it, expect, etc. globally. Vitest does too when
globals: true is set. If you prefer explicit imports (recommended for IDE
support), add them:
// Before (Jest - globals implicit)
describe('Cart', () => { ... });
// After option A - keep globals: true in config, no import needed
describe('Cart', () => { ... });
// After option B - explicit imports (preferred for type safety)
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';For automated codemod, use:
npx @vitest/codemod --type=jest-to-vitest src/**/*.test.ts5. Replace Jest-specific globals with Vitest equivalents
| Jest | Vitest | Notes |
|---|---|---|
jest.fn() |
vi.fn() |
Direct replacement |
jest.spyOn(obj, 'method') |
vi.spyOn(obj, 'method') |
Direct replacement |
jest.mock('module') |
vi.mock('module') |
Direct replacement |
jest.resetAllMocks() |
vi.resetAllMocks() |
Direct replacement |
jest.clearAllMocks() |
vi.clearAllMocks() |
Direct replacement |
jest.restoreAllMocks() |
vi.restoreAllMocks() |
Direct replacement |
jest.useFakeTimers() |
vi.useFakeTimers() |
Direct replacement |
jest.advanceTimersByTime(n) |
vi.advanceTimersByTime(n) |
Direct replacement |
jest.runAllTimers() |
vi.runAllTimers() |
Direct replacement |
jest.requireActual('m') |
vi.importActual('m') |
Returns a Promise in Vitest |
jest.requireMock('m') |
vi.importMock('m') |
Returns a Promise in Vitest |
jest.setTimeout(n) |
{ timeout: n } option on it/describe |
Or vi.setConfig({ testTimeout: n }) |
6. Handle vi.importActual - it's async
In Jest, jest.requireActual is synchronous. In Vitest, vi.importActual is
async and must be awaited inside a factory function:
// Jest
jest.mock('./config', () => ({
...jest.requireActual('./config'),
API_URL: 'http://localhost',
}));
// Vitest
vi.mock('./config', async (importOriginal) => {
const actual = await importOriginal<typeof import('./config')>();
return {
...actual,
API_URL: 'http://localhost',
};
});7. Update snapshot files (optional)
Vitest uses the same .snap format as Jest. Existing snapshot files continue
to work without modification. If you want to regenerate them cleanly:
npx vitest run --updateSnapshotAPI differences and gotchas
vi.mock hoisting
Both Jest and Vitest hoist vi.mock / jest.mock calls to the top of the
file before any imports. Vitest enforces this more strictly - if you try to
use a variable defined outside the vi.mock factory, you will get an error
unless the variable name starts with mock:
// This fails in Vitest - "returnValue" is not accessible in hoisted scope
const returnValue = { id: 1 };
vi.mock('./service', () => ({ getUser: vi.fn(() => returnValue) }));
// Fix: prefix the variable with "mock"
const mockReturnValue = { id: 1 };
vi.mock('./service', () => ({ getUser: vi.fn(() => mockReturnValue) }));expect.assertions behavior
expect.assertions(n) works in Vitest. Prefer await expect(p).rejects.toThrow()
over expect.assertions for async error testing - it is more explicit.
Module resolution
Vitest resolves modules through Vite's resolver. If your tsconfig.json has
path aliases (@/*), they work automatically in Vitest - no extra config
needed. In Jest, you need moduleNameMapper.
// jest.config.js - required for aliases
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
}
// vitest.config.ts - aliases from vite.config.ts are inherited automatically
// No extra config needed if vite.config.ts already has resolve.aliastestEnvironment per file
Vitest supports per-file environment overrides via a docblock comment, which is handy for mixed node/browser test suites:
// @vitest-environment node
import { describe, it } from 'vitest';
// This file runs in Node even if the default environment is jsdomTimer mocks - Date and performance.now
// Vitest fake timers also mock Date by default
vi.useFakeTimers();
vi.setSystemTime(new Date('2024-01-15T10:00:00Z'));
expect(new Date().toISOString()).toBe('2024-01-15T10:00:00.000Z');
vi.useRealTimers();
// In Jest you need jest.setSystemTime separately
jest.useFakeTimers();
jest.setSystemTime(new Date('2024-01-15T10:00:00Z'));Removing Jest after migration
Once all tests pass under Vitest:
npm uninstall jest @types/jest babel-jest ts-jest jest-environment-jsdom
# Remove jest.config.js
rm jest.config.js
# Remove babel.config.js if it was only used for Jest transformsCheck package.json for any lingering "jest" config keys and remove them.
Common migration errors
| Error | Cause | Fix |
|---|---|---|
ReferenceError: vi is not defined |
globals: true not set and no import |
Add import { vi } from 'vitest' or set globals: true |
Cannot use import statement |
ESM module not transformed | Add the package to server.deps.inline in vitest config |
vi.mock() variable out of scope |
Variable not prefixed with mock |
Rename variable to mockXxx |
Cannot find module './setup' |
Wrong path in setupFiles |
Use path relative to project root, not the config file |
| Snapshot mismatch on first run | Snapshots from Jest are stale | Run npx vitest run --updateSnapshot |
TypeError: Cannot read properties of undefined |
vi.resetAllMocks() not called between tests |
Add afterEach(() => vi.resetAllMocks()) or clearMocks: true in config |
Frequently Asked Questions
What is jest-vitest?
Use this skill when writing unit tests with Jest or Vitest, implementing mocking strategies, configuring test runners, or improving test coverage. Triggers on Jest, Vitest, describe/it/expect, mocking, vi.fn, jest.fn, snapshot testing, test coverage, and any task requiring JavaScript/TypeScript unit testing.
How do I install jest-vitest?
Run npx skills add AbsolutelySkilled/AbsolutelySkilled --skill jest-vitest in your terminal. The skill will be immediately available in your AI coding agent.
What AI agents support jest-vitest?
jest-vitest works with claude-code, gemini-cli, openai-codex. Install it once and use it across any supported AI coding agent.