← 返回
内容创作 中文

Jest

Jest best practices, patterns, and API guidance for JavaScript/TypeScript testing. Covers mock design, async testing, matchers, timer mocks, snapshots, modul...
Jest 最佳实践、设计模式和 JavaScript/TypeScript 测试 API 指南。涵盖 Mock 设计、异步测试、匹配器、定时器 Mock、快照、模块...
anivar
内容创作 clawhub v1.0.0 1 版本 100000 Key: 无需
★ 0
Stars
📥 555
下载
💾 10
安装
1
版本
#latest

概述

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.

NeedRecommended Tool
-----------------------
Unit/integration testing (JS/TS)Jest
React component testingJest + React Testing Library
E2E browser testingPlaywright, Cypress
API contract testingJest + Supertest
Smaller/faster test runnerVitest (Jest-compatible API)
Native ESM without configVitest or Node test runner

Rule Categories by Priority

PriorityCategoryImpactPrefix
------------------------------------
1Mock DesignCRITICALmock- (5 rules)
2Async TestingCRITICALasync-
3Matcher UsageHIGHmatcher-
4Timer MockingHIGHtimer-
5Test StructureHIGHstructure-
6Module MockingMEDIUMmodule-
7Snapshot TestingMEDIUMsnapshot-
8ConfigurationMEDIUMconfig-
9Performance & CIMEDIUMperf-

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

APIPurpose
--------------
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

PriorityReferenceWhen to read
----------------------------------
1references/matchers.mdAll matchers: equality, truthiness, numbers, strings, arrays, objects, asymmetric, custom
2references/mock-functions.mdjest.fn, jest.spyOn, .mock property, return values, implementations
3references/jest-object.mdjest.mock, jest.useFakeTimers, jest.setTimeout, jest.retryTimes
4references/async-patterns.mdPromises, async/await, done callbacks, .resolves/.rejects
5references/configuration.mdtestMatch, transform, moduleNameMapper, coverage, environments
6references/snapshot-testing.mdtoMatchSnapshot, inline snapshots, property matchers, serializers
7references/module-mocking.mdManual mocks, __mocks__, ESM mocking, partial mocking
8references/anti-patterns.md15 common mistakes with BAD/GOOD examples
9references/ci-and-debugging.mdCI 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 needCompanion skillWhat it covers
---------
API mocking (network-level)mswMSW 2.0 handlers, setupServer, server.use() per-test overrides, HttpResponse.json(), GraphQL mocking, concurrent test isolation
React Native componentsreact-native-testingRNTL v13/v14 queries (getByRole, findBy), userEvent, fireEvent, waitFor, async render patterns
Zod schema validationzod-testingsafeParse() result testing, z.flattenError() assertions, z.toJSONSchema() snapshot drift, zod-schema-faker mock data, property-based testing
Redux-Saga side effectsredux-saga-testingexpectSaga integration tests, testSaga unit tests, providers, reducer integration, cancellation testing
Java testingjava-testingJUnit 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

版本历史

共 1 个版本

  • v1.0.0 当前
    2026-03-30 11:55 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

productivity

Zod Testing

anivar
使用 Jest 和 Vitest 测试 Zod 模式的模式。涵盖模式正确性测试、模拟数据生成、错误断言模式、集成测试……
★ 0 📥 745
content-creation

AdMapix

fly0pants
广告情报与应用数据分析助手,支持搜索广告素材、分析应用排名、下载量、收入及市场洞察,用于广告素材和竞品分析。
★ 294 📥 136,367
content-creation

Humanizer

biostartechnology
消除AI写作痕迹,使文本更自然真实。基于维基百科"AI写作特征"指南,识别并修正夸张象征、宣传用语、肤浅-ing分析、模糊归因、破折号滥用、三项排比、AI词汇、负面平行结构及冗长连接词等模式。
★ 858 📥 199,026