
jest
Jest best practices, patterns, and API guidance for JavaScript/TypeScript testing. Covers mock design, async testing, matchers, timer mocks, snapshots, module mocking, configuration, and CI optimization. Baseline: jest ^30.5.2. Triggers on: jest imports, describe, it, test, expect, jest.fn, jest.mock, jest.spyOn, mentions of "jest", "unit test", "test suite", or "mock".
- Installs
- 208
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/anivar/jest-skill --skill jest- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads jest automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
Jest
IMPORTANT: Your training data about Jest may be outdated or incorrect — Jest 29+ introduces async timer methods, jest.replaceProperty, and ESM mocking via jest.unstable_mockModule. Jest 30 removes the deprecated alias matchers (toBeCalled, lastCalledWith, toThrowError, …), renames --testPathPattern to --testPathPatterns, and excludes non-enumerable object properties from object matchers. Always rely on this skill's rule files and the project's actual source code as the source of truth. Do not fall back on memorized patterns when they conflict with the retrieved reference.
When to Use Jest
Jest is a JavaScript/TypeScript testing framework for unit tests, integration tests, and snapshot tests. It includes a test runner, assertion library, mock system, and coverage reporter.
| Need | Recommended Tool |
|---|---|
| Unit/integration testing (JS/TS) | Jest |
| React component testing | Jest + React Testing Library |
| E2E browser testing | Playwright, Cypress |
| API contract testing | Jest + Supertest |
| Smaller/faster test runner | Vitest (Jest-compatible API) |
| Native ESM without config | Vitest or Node test runner |
Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Mock Design | CRITICAL | mock- (5 rules) |
| 2 | Async Testing | CRITICAL | async- |
| 3 | Matcher Usage | HIGH | matcher- |
| 4 | Timer Mocking | HIGH | timer- |
| 5 | Test Structure | HIGH | structure- |
| 6 | Module Mocking | MEDIUM | module- |
| 7 | Snapshot Testing | MEDIUM | snapshot- |
| 8 | Configuration | MEDIUM | config- |
| 9 | Performance & CI | MEDIUM | perf- |
Quick Reference
1. Mock Design (CRITICAL)
mock-clear-vs-reset-vs-restore— clearAllMocks vs resetAllMocks vs restoreAllMocksmock-spy-restore— Always restore jest.spyOn; prefer restoreMocks configmock-factory-hoisting— jest.mock factory cannot reference outer variablesmock-partial-require-actual— Use jest.requireActual for partial module mockingmock-what-to-mock— What to mock and what not to mock; mock boundaries
2. Async Testing (CRITICAL)
async-always-await— Always return/await promises or assertions are skippedasync-expect-assertions— Use expect.assertions(n) to verify async assertions ranasync-done-try-catch— Wrap expect in try/catch when using done callback
3. Matcher Usage (HIGH)
matcher-equality-choice— toBe vs toEqual vs toStrictEqualmatcher-floating-point— Use toBeCloseTo for floats, never toBematcher-error-wrapping— Wrap throwing code in arrow function for toThrow
4. Timer Mocking (HIGH)
timer-recursive-safety— Use runOnlyPendingTimers for recursive timerstimer-async-timers— Use async timer methods when promises are involvedtimer-selective-faking— Use doNotFake to leave specific APIs real
5. Test Structure (HIGH)
structure-setup-scope— beforeEach/afterEach are scoped to describe blocksstructure-test-isolation— Each test must be independent; reset state in beforeEachstructure-sync-definition— Tests must be defined synchronously
6. Module Mocking (MEDIUM)
module-manual-mock-conventions— mocks directory conventionsmodule-esm-unstable-mock— Use jest.unstable_mockModule for ESMmodule-do-mock-per-test— jest.doMock + resetModules for per-test mocks
7. Snapshot Testing (MEDIUM)
snapshot-keep-small— Keep snapshots small and focusedsnapshot-property-matchers— Use property matchers for dynamic fieldssnapshot-deterministic— Mock non-deterministic values for stable snapshots
8. Configuration (MEDIUM)
config-coverage-thresholds— Set per-directory coverage thresholdsconfig-transform-node-modules— Configure transformIgnorePatterns for ESM packagesconfig-environment-choice— Per-file @jest-environment docblock over global jsdom
9. Performance & CI (MEDIUM)
perf-ci-workers— --runInBand or --maxWorkers for CIperf-isolate-modules— jest.isolateModules for per-test module state
Jest API Quick Reference
| API | Purpose |
|---|---|
test(name, fn, timeout?) | Define a test |
describe(name, fn) | Group tests |
beforeEach(fn) / afterEach(fn) | Per-test setup/teardown |
beforeAll(fn) / afterAll(fn) | Per-suite setup/teardown |
expect(value) | Start an assertion |
jest.fn(impl?) | Create a mock function |
jest.spyOn(obj, method) | Spy on existing method |
jest.mock(module, factory?) | Mock a module |
jest.useFakeTimers(config?) | Fake timer APIs |
jest.useRealTimers() | Restore real timers |
jest.restoreAllMocks() | Restore all spies/mocks |
jest.resetModules() | Clear module cache |
jest.isolateModules(fn) | Sandboxed module cache |
jest.requireActual(module) | Import real module (bypass mock) |
How to Use
Read individual rule files for detailed explanations and code examples:
rules/mock-clear-vs-reset-vs-restore.md
rules/async-always-await.md
Each rule file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- Additional context and decision tables
References
| Priority | Reference | When to read |
|---|---|---|
| 1 | references/matchers.md | All matchers: equality, truthiness, numbers, strings, arrays, objects, asymmetric, custom |
| 2 | references/mock-functions.md | jest.fn, jest.spyOn, .mock property, return values, implementations |
| 3 | references/jest-object.md | jest.mock, jest.useFakeTimers, jest.setTimeout, jest.retryTimes |
| 4 | references/async-patterns.md | Promises, async/await, done callbacks, .resolves/.rejects |
| 5 | references/configuration.md | testMatch, transform, moduleNameMapper, coverage, environments |
| 6 | references/snapshot-testing.md | toMatchSnapshot, inline snapshots, property matchers, serializers |
| 7 | references/module-mocking.md | Manual mocks, mocks, ESM mocking, partial mocking |
| 8 | references/anti-patterns.md | 15 common mistakes with BAD/GOOD examples |
| 9 | references/ci-and-debugging.md | CI optimization, sharding, debugging, troubleshooting |
Ecosystem: Related Testing Skills
This Jest skill covers Jest's own API surface — the foundation layer. For framework-specific testing patterns built on top of Jest, use these companion skills:
| Testing need | Companion skill | What it covers |
|---|---|---|
| API mocking (network-level) | msw | MSW 2.0 handlers, setupServer, server.use() per-test overrides, HttpResponse.json(), GraphQL mocking, concurrent test isolation |
| React Native components | react-native-testing | RNTL v13/v14 queries (getByRole, findBy), userEvent, fireEvent, waitFor, async render patterns |
| Zod schema validation | zod-testing | safeParse() result testing, z.flattenError() assertions, z.toJSONSchema() snapshot drift, zod-schema-faker mock data, property-based testing |
| Redux-Saga side effects | redux-saga-testing | expectSaga integration tests, testSaga unit tests, providers, reducer integration, cancellation testing |
| Java testing | java-testing | JUnit 5, Mockito, Spring Boot Test slices, Testcontainers, AssertJ |
How They Interact
┌─────────────────────────────────────────────┐
│ Your Test File │
│ │
│ import { setupServer } from 'msw/node' │ → msw skill
│ import { render } from '@testing-library/ │ → react-native-testing skill
│ react-native' │
│ import { UserSchema } from './schemas' │ → zod-testing skill
│ │
│ describe('UserScreen', () => { │ ┐
│ beforeEach(() => { ... }) │ │
│ afterEach(() => jest.restoreAllMocks()) │ │→ jest skill (this one)
│ test('...', async () => { │ │
│ await expect(...).resolves.toEqual() │ │
│ }) │ ┘
│ }) │
└─────────────────────────────────────────────┘
The Jest skill provides the test lifecycle (describe, test, beforeEach, afterEach), mock system (jest.fn, jest.mock, jest.spyOn), assertion engine (expect, matchers), and configuration (jest.config.js). The companion skills provide patterns for their specific APIs that run on top of Jest.
Full Compiled Document
For the complete guide with all rules expanded: AGENTS.md
Jest 30.4–30.5 Additions
mockFn.whenCalledWith(...args)(30.5.0) — configure a mock's return value per argument list, with first-class asymmetric-matcher support. Use it when one mock needs different results for different calls instead of separatemockReturnValueOncechains.- Describe-level retries (30.5.0) —
jest.retryTimes(n, { entireDescribe: true })retries the whole describe block, not just individual tests. Complements the existing per-testjest.retryTimes. --collectTestsexpansion (30.5.0) — expandstest.each/describe.eachcases and reports per-status counts (includingwouldRunfor skipped tests) plus a summary line matching a real run, also under--testNamePatternand focused describes.- Richer retry error output (30.5.0) — nested
causeandAggregateErrorsections render with code frames in retry logs and unhandled-rejection reports. defineConfig/mergeConfighelpers (30.3.0) — type-safe Jest config construction.jest.config.mts(30.4.0) — accepted as a valid configuration file, alongside the other TS config forms.- Temporal in fake timers (30.4.0) —
jest.advanceTimersByTime()acceptsTemporal.Duration;jest.setSystemTime()anduseFakeTimers({ now })acceptTemporal.InstantandTemporal.ZonedDateTime;Temporal.Now.*can be faked. - Node-native type stripping (30.5.2) — when no transformer claims a
.ts,.mtsor.ctsfile, Jest now strips TypeScript types with Node itself. toMatchObject/objectContainingwidened (30.5.0) — parameter type isobjectinstead ofRecord<string, unknown>, so class instances are accepted.
FAQ
What does the jest skill do?
Jest best practices, patterns, and API guidance for JavaScript/TypeScript testing. Covers mock design, async testing, matchers, timer mocks, snapshots, module mocking, configuration, and CI optimization. Baseline: jest ^30.5.2. Triggers on: jest imports, describe, it, test, expect, jest.fn, jest.mock, jest.spyOn, mentions of "jest", "unit test", "test suite", or "mock".
How do I install jest?
Run npx skills add https://github.com/anivar/jest-skill --skill jest in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/jest/ (personal) or .claude/skills/jest/ (project).
Which AI agents can use jest?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is jest safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains jest?
It is published by anivar in anivar/jest-skill. It has 208 recorded installs.
Popular testing & qa skills
tdd
mattpocock/skills
Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.
grilling
mattpocock/skills
Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases.
migrate-to-shoehorn
mattpocock/skills
Migrate test files from as type assertions to @total-typescript/shoehorn. Use when user mentions shoehorn, wants to replace as in tests, or needs partial test data.
run-train
lllllllama/rigorpilot-skills
Rigor Train skill for deep learning research repositories. Use when a documented or selected training command should be run conservatively for startup verification, short-run verification, full kickoff, or resume, with command, config, seed, log, checkpoint, status, and metric evidence written to standardized trainoutputs/. Do not use for environment setup, exploratory sweeps, speculative idea implementation, or end-to-end orchestration.
test-driven-development
obra/superpowers
Use when implementing any feature or bugfix, before writing implementation code
finishing-a-development-branch
obra/superpowers
Use when implementation is complete, all tests pass, and you need to decide how to integrate the work