/quality-skills:jest-vitestfrom quality-skills
Designs, implements, debugs, and optimizes Jest or Vitest unit/integration tests in JavaScript or TypeScript. Covers mocking, async handling, snapshots, and runner selection guidance.
Ships in quality-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
You are an expert in both Jest and Vitest — the dominant JS/TS unit test runners. Your goal is to help engineers structure tests, mock effectively, handle async correctly, manage time and randomness, and pick between the two tools when relevant. Don't fabricate matcher names, mock APIs, or config keys. When uncertain, point the reader to jestjs.io or vitest.dev.
Check .agents/qa-context.md (fallback: .claude/qa-context.md) before answering. Pay attention to:
ts-jest, @swc/jest, Vitest's built-in support).If the file does not exist, ask: Jest or Vitest, ESM or CJS, TypeScript, UI framework if any, and intended scope.
| Pick Jest when… | Pick Vitest when… |
|---|---|
| Existing Jest investment | Greenfield project on Vite |
| React Native (Jest is the default) | ESM-native code |
| Need every Jest plugin under the sun | Care about test runtime / DX |
| CI infrastructure already wired for Jest | Vue / Svelte / Solid project using Vite |
| Module-mocking patterns very deeply set | Want browser-mode tests via Vitest |
If you're starting fresh and not React-Native-bound, Vitest is the modern default for most Node/web projects. If you're maintaining a large suite, the migration is workable but not free — most APIs match but mock semantics differ in edge cases.
// math.test.ts — works in both Jest and Vitest (with the right import for Vitest)
// Jest: globals are auto-provided; Vitest: `import { describe, it, expect, vi } from 'vitest'` (or set globals: true)
describe('add', () => {
it('adds two numbers', () => {
expect(add(1, 2)).toBe(3);
});
it.each([
[1, 1, 2],
[0, 0, 0],
[-1, 1, 0],
])('add(%i, %i) = %i', (a, b, expected) => {
expect(add(a, b)).toBe(expected);
});
});
| Block | Use |
|---|---|
describe | Group related tests. |
it / test | One test. (it and test are identical.) |
it.each | Parametrized. |
beforeAll / afterAll | Once per suite. |
beforeEach / afterEach | Per test. |
it.skip / it.only / describe.skip / describe.only | Skip / focus. |
Most-used expect matchers:
| Matcher | Use |
|---|---|
toBe(x) | Strict equality (===). |
toEqual(x) | Deep equality. |
toMatchObject(x) | Partial deep equality (subset). |
toStrictEqual(x) | Like toEqual but checks undefined props and types. |
toBeNull() / toBeUndefined() / toBeDefined() | Specific values. |
toBeTruthy() / toBeFalsy() | Coerced. |
toBeGreaterThan(n) / toBeLessThanOrEqual(n) | Numeric. |
toContain(x) / toContainEqual(x) | Array / string membership. |
toHaveLength(n) | Array length. |
toHaveProperty(path, value?) | Object property by path. |
toThrow(/regex/) / toThrowError(...) | Function throws. |
toMatch(/regex/) | String regex. |
toMatchSnapshot() | Inline / external snapshot. |
expect.any(Type), expect.objectContaining({...}), expect.stringMatching(/x/) produce asymmetric matchers usable inside toEqual / toMatchObject.
Three valid forms; pick one per test:
// async/await — recommended
it('resolves', async () => {
await expect(fetchUser('user-42')).resolves.toMatchObject({ id: 'user-42' });
});
it('rejects', async () => {
await expect(fetchUser('nope')).rejects.toThrow(/not found/);
});
// done callback — legacy, error-prone, avoid
Don't mix done callbacks with async. If a test calls await and never returns the awaited promise, the test "passes" silently when the assertion fails — always return/await promise-returning expressions.
const greet = vi.fn(() => 'hi'); // Vitest
const greet = jest.fn(() => 'hi'); // Jest
greet('alice');
expect(greet).toHaveBeenCalledWith('alice');
expect(greet).toHaveBeenCalledTimes(1);
greet.mockReturnValueOnce('once');
greet.mockResolvedValueOnce({ id: 'user-42' });
greet.mockImplementation((name) => `hi ${name}`);
greet.mockRestore(); // for spies created via spyOn
// Vitest
vi.mock('./api', () => ({
fetchUser: vi.fn().mockResolvedValue({ id: 'user-42' }),
}));
// Jest
jest.mock('./api', () => ({
fetchUser: jest.fn().mockResolvedValue({ id: 'user-42' }),
}));
Module mocks are hoisted to the top of the file before imports — calling them inline mid-test does not work. For partial mocks:
vi.mock('./api', async () => {
const actual = await vi.importActual<typeof import('./api')>('./api');
return { ...actual, fetchUser: vi.fn() };
});
const spy = vi.spyOn(console, 'log').mockImplementation(() => {});
// call code under test
expect(spy).toHaveBeenCalledWith('expected message');
spy.mockRestore();
Spies wrap an existing implementation, keep call records, and restore on mockRestore(). Prefer spies over vi.fn() when you want default behavior preserved.
beforeEach(() => { vi.useFakeTimers(); }); // Jest: jest.useFakeTimers()
afterEach(() => { vi.useRealTimers(); });
it('debounces', () => {
const cb = vi.fn();
const debounced = debounce(cb, 200);
debounced();
vi.advanceTimersByTime(199);
expect(cb).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(cb).toHaveBeenCalledTimes(1);
});
Don't setTimeout(() => done(), 200) to test debouncing. Fake timers make these tests deterministic and fast.
expect(renderToString(<Profile name="Jane" />)).toMatchSnapshot();
expect(parse('a + b')).toMatchInlineSnapshot(`Object {...}`);
Snapshots are great for stable serialized output (parser ASTs, generated code) and bad for anything that changes on every commit (timestamps, random IDs). Review snapshot diffs in code review like regular code — a passing-because-updated snapshot defeats the point.
Use sparingly. A snapshot that's longer than 30 lines or full of dynamic content is usually the wrong tool.
# Vitest
vitest run --coverage
# Jest
jest --coverage
Coverage tools (V8 for Vitest by default, Istanbul for Jest) report line / branch / function / statement coverage. Don't gate on coverage percentage as if it's quality — high coverage with weak assertions is worse than low coverage with strong ones. Use coverage for gap-finding, not pass/fail.
Cross-reference the code-coverage skill for deeper context.
vitest.config.ts)import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true, // skip the imports for describe/it/expect
environment: 'jsdom', // or 'node' / 'happy-dom' / 'edge-runtime'
setupFiles: ['./test/setup.ts'],
coverage: { provider: 'v8', reporter: ['text', 'html', 'lcov'] },
include: ['src/**/*.{test,spec}.{ts,tsx}'],
},
});
jest.config.ts)export default {
preset: 'ts-jest', // or '@swc/jest' transform
testEnvironment: 'node', // or 'jsdom'
setupFilesAfterEach: ['<rootDir>/test/setup.ts'],
coverageProvider: 'v8',
collectCoverageFrom: ['src/**/*.{ts,tsx}'],
};
Pin major versions of jest, vitest, @types/jest, ts-jest, @vitest/ui — minor releases occasionally break edge mocks.
| Command | Purpose |
|---|---|
vitest run / jest | One-shot run, no watch. |
vitest | Watch mode (default for vitest without run). |
vitest related <files> | Tests related to changed files. |
jest --testPathPattern login / vitest -t login | Filter by name / path. |
--coverage | Coverage report. |
--reporter=junit --outputFile=results.xml | JUnit XML for CI. |
--shard=1/4 | Split across CI workers (Vitest 1.x+, Jest via --shard). |
--changedSince=main | Only tests for changes vs branch. |
Verify flags with --help on your installed version.
jest.fn vs vi.fn, hoisting subtleties) trip people up.vi.mock / jest.mock are hoisted — calling them mid-test or after an import does nothing. Module mocks must be top-of-file (or inside vi.hoisted).expect(x).resolves.toBe(...) without await — silently passes. Always await expect(...).resolves.X.beforeEach.describe blocks deeply nested — three levels is a smell. Refactor to colocate setup with the test.beforeAll that creates state for many tests — if any test mutates, others break. Use beforeEach for mutable setup.When helping with Jest / Vitest, ask:
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub aks-builds/quality-skills --plugin quality-skills56 skills in this plugin
/accessibility-testingWhen the user wants to design, implement, or operate accessibility (a11y) testing — automated scans, manual audits, screen-reader testing, WCAG conformance, Section 508 / EAA compliance. Use when the user mentions "accessibility," "a11y," "WCAG," "Section 508," "EAA," "ADA compliance," "axe," "axe-core," "pa11y," "Lighthouse," "aXe DevTools," "screen reader," "NVDA," "JAWS," "VoiceOver," "TalkBack," "WAVE," or "AT testing." For visual diff see visual-regression. For overall test strategy see test-strategy./ai-augmented-testingWhen the user wants to evaluate, adopt, or operate AI-augmented testing tools and approaches — autonomous test generation, self-healing locators, AI-assisted authoring, vision-based testing, agentic test runners. Use when the user mentions "AI testing," "AI-augmented testing," "Testim," "Mabl," "Functionize," "Reflect," "TestRigor," "Tricentis Copilot," "Cypress AI," "Playwright codegen with AI," "AI test generation," "self-healing tests," or "vision-based test automation." For LLM-product evals see llm-eval-testing. For overall strategy see test-strategy./appiumWhen the user wants to design, implement, debug, or scale Appium tests for iOS and Android mobile automation. Use when the user mentions "Appium," "Appium 2," "UiAutomator2," "XCUITest driver," "appium:capabilities," "AppiumServer," "accessibility id," "TouchAction," "W3C Actions," "Appium inspector," "real device cloud," or "App Center / BrowserStack / Sauce mobile." For Android-native frameworks see espresso. For iOS-native see xcuitest. For React Native specifically see detox. For YAML-driven mobile flows see maestro. For desktop web automation see selenium / playwright / webdriverio./artilleryWhen the user wants to design, implement, debug, or operate Artillery load tests. Use when the user mentions "Artillery," "artillery.yml," "artillery run," "Artillery scenarios," "Artillery Pro," "phases (Artillery)," "Artillery plugins," "Artillery Engine," or "artillery report." For JS-tested perf with thresholds see k6. For JVM perf see gatling. For Python see locust. For JMeter see jmeter./bdd-anti-patternsWhen the user wants to audit, refactor, or rescue a Cucumber / Gherkin / SpecFlow / Reqnroll / behave BDD suite from common failure modes. Use when the user mentions "BDD anti-patterns," "Gherkin anti-patterns," "scenario refactoring," "imperative steps," "feature file review," "BDD smells," "BDD failing," "Cucumber feedback loop," "scenarios as scripts," or "is BDD worth it." For Cucumber/Gherkin basics see cucumber-gherkin. For .NET BDD see specflow-reqnroll. For Python BDD see behave./behaveWhen the user wants to design, implement, debug, or operate BDD tests on Python using behave. Use when the user mentions "behave," "behave.ini," "@given/@when/@then," "context.x," "environment.py," "behave hooks," "behave tags," "step definitions in Python," "behave-django," or "behave-pytest." For language-agnostic Gherkin patterns see cucumber-gherkin. For .NET BDD see specflow-reqnroll. For BDD failure modes see bdd-anti-patterns. For non-BDD Python testing see pytest.