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 ^29.0.0 / ^30.0.0. Triggers on: jest imports, describe, it, test, expect, jest.fn, jest.mock, jest.spyOn, mentions of "jest", "unit test", "test suite", or "mock".
Best use case
jest is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
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 ^29.0.0 / ^30.0.0. Triggers on: jest imports, describe, it, test, expect, jest.fn, jest.mock, jest.spyOn, mentions of "jest", "unit test", "test suite", or "mock".
Teams using jest should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/jest-skill/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How jest Compares
| Feature / Agent | jest | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this 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 ^29.0.0 / ^30.0.0. Triggers on: jest imports, describe, it, test, expect, jest.fn, jest.mock, jest.spyOn, mentions of "jest", "unit test", "test suite", or "mock".
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
AI Agent for YouTube Script Writing
Find AI agent skills for YouTube script writing, video research, content outlining, and repeatable channel production workflows.
AI Agents for Marketing
Discover AI agents for marketing workflows, from SEO and content production to campaign research, outreach, and analytics.
SKILL.md Source
# 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 deprecates the `done` callback in favor of async patterns. 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 restoreAllMocks
- `mock-spy-restore` — Always restore jest.spyOn; prefer restoreMocks config
- `mock-factory-hoisting` — jest.mock factory cannot reference outer variables
- `mock-partial-require-actual` — Use jest.requireActual for partial module mocking
- `mock-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 skipped
- `async-expect-assertions` — Use expect.assertions(n) to verify async assertions ran
- `async-done-try-catch` — Wrap expect in try/catch when using done callback
### 3. Matcher Usage (HIGH)
- `matcher-equality-choice` — toBe vs toEqual vs toStrictEqual
- `matcher-floating-point` — Use toBeCloseTo for floats, never toBe
- `matcher-error-wrapping` — Wrap throwing code in arrow function for toThrow
### 4. Timer Mocking (HIGH)
- `timer-recursive-safety` — Use runOnlyPendingTimers for recursive timers
- `timer-async-timers` — Use async timer methods when promises are involved
- `timer-selective-faking` — Use doNotFake to leave specific APIs real
### 5. Test Structure (HIGH)
- `structure-setup-scope` — beforeEach/afterEach are scoped to describe blocks
- `structure-test-isolation` — Each test must be independent; reset state in beforeEach
- `structure-sync-definition` — Tests must be defined synchronously
### 6. Module Mocking (MEDIUM)
- `module-manual-mock-conventions` — __mocks__ directory conventions
- `module-esm-unstable-mock` — Use jest.unstable_mockModule for ESM
- `module-do-mock-per-test` — jest.doMock + resetModules for per-test mocks
### 7. Snapshot Testing (MEDIUM)
- `snapshot-keep-small` — Keep snapshots small and focused
- `snapshot-property-matchers` — Use property matchers for dynamic fields
- `snapshot-deterministic` — Mock non-deterministic values for stable snapshots
### 8. Configuration (MEDIUM)
- `config-coverage-thresholds` — Set per-directory coverage thresholds
- `config-transform-node-modules` — Configure transformIgnorePatterns for ESM packages
- `config-environment-choice` — Per-file @jest-environment docblock over global jsdom
### 9. Performance & CI (MEDIUM)
- `perf-ci-workers` — --runInBand or --maxWorkers for CI
- `perf-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`Related Skills
---
name: article-factory-wechat
humanizer
Remove signs of AI-generated writing from text. Use when editing or reviewing text to make it sound more natural and human-written. Based on Wikipedia's comprehensive "Signs of AI writing" guide. Detects and fixes patterns including: inflated symbolism, promotional language, superficial -ing analyses, vague attributions, em dash overuse, rule of three, AI vocabulary words, negative parallelisms, and excessive conjunctive phrases.
find-skills
Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.
tavily-search
Use Tavily API for real-time web search and content extraction. Use when: user needs real-time web search results, research, or current information from the web. Requires Tavily API key.
baidu-search
Search the web using Baidu AI Search Engine (BDSE). Use for live information, documentation, or research topics.
agent-autonomy-kit
Stop waiting for prompts. Keep working.
Meeting Prep
Never walk into a meeting unprepared again. Your agent researches all attendees before calendar events—pulling LinkedIn profiles, recent company news, mutual connections, and conversation starters. Generates a briefing doc with talking points, icebreakers, and context so you show up informed and confident. Triggered automatically before meetings or on-demand. Configure research depth, advance timing, and output format. Walking into meetings blind is amateur hour—missed connections, generic small talk, zero leverage. Use when setting up meeting intelligence, researching specific attendees, generating pre-meeting briefs, or automating your prep workflow.
self-improvement
Captures learnings, errors, and corrections to enable continuous improvement. Use when: (1) A command or operation fails unexpectedly, (2) User corrects Claude ('No, that's wrong...', 'Actually...'), (3) User requests a capability that doesn't exist, (4) An external API or tool fails, (5) Claude realizes its knowledge is outdated or incorrect, (6) A better approach is discovered for a recurring task. Also review learnings before major tasks.
botlearn-healthcheck
botlearn-healthcheck — BotLearn autonomous health inspector for OpenClaw instances across 5 domains (hardware, config, security, skills, autonomy); triggers on system check, health report, diagnostics, or scheduled heartbeat inspection.
linkedin-cli
A bird-like LinkedIn CLI for searching profiles, checking messages, and summarizing your feed using session cookies.
notebooklm
Google NotebookLM 非官方 Python API 的 OpenClaw Skill。支持内容生成(播客、视频、幻灯片、测验、思维导图等)、文档管理和研究自动化。当用户需要使用 NotebookLM 生成音频概述、视频、学习材料或管理知识库时触发。
小红书长图文发布 Skill
## 概述