본문으로 건너뛰기
cccskills
무료GitHub에 공개

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".

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(44)

  • SKILL.md11.1 KB
  • .claude/settings.local.json69 B
  • .github/FUNDING.yml92 B
  • AGENTS.md19.4 KB
  • CHANGELOG.md7.4 KB
  • LICENSE1.0 KB
  • README.md6.0 KB
  • references/anti-patterns.md4.8 KB
  • references/async-patterns.md4.4 KB
  • references/ci-and-debugging.md6.9 KB
  • references/configuration.md8.6 KB
  • references/jest-object.md8.3 KB
  • references/matchers.md6.7 KB
  • references/mock-functions.md5.4 KB
  • references/module-mocking.md6.8 KB
  • references/snapshot-testing.md5.7 KB
  • rules/async-always-await.md2.1 KB
  • rules/async-done-try-catch.md2.6 KB
  • rules/async-expect-assertions.md2.3 KB
  • rules/config-coverage-thresholds.md2.4 KB
  • rules/config-environment-choice.md2.7 KB
  • rules/config-transform-node-modules.md2.8 KB
  • rules/matcher-equality-choice.md2.6 KB
  • rules/matcher-error-wrapping.md2.6 KB
  • rules/matcher-floating-point.md1.9 KB
  • rules/mock-clear-vs-reset-vs-restore.md2.5 KB
  • rules/mock-factory-hoisting.md2.0 KB
  • rules/mock-partial-require-actual.md2.4 KB
  • rules/mock-spy-restore.md3.7 KB
  • rules/mock-what-to-mock.md5.5 KB
  • rules/module-do-mock-per-test.md2.8 KB
  • rules/module-esm-unstable-mock.md4.1 KB
  • rules/module-manual-mock-conventions.md3.3 KB
  • rules/perf-ci-workers.md2.5 KB
  • rules/perf-isolate-modules.md4.0 KB
  • rules/snapshot-deterministic.md2.8 KB
  • rules/snapshot-keep-small.md2.4 KB
  • rules/snapshot-property-matchers.md3.0 KB
  • rules/structure-setup-scope.md2.4 KB
  • rules/structure-sync-definition.md2.6 KB
  • rules/structure-test-isolation.md2.4 KB
  • rules/timer-async-timers.md2.5 KB
  • rules/timer-recursive-safety.md3.9 KB
  • rules/timer-selective-faking.md3.7 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

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.

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

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 separate mockReturnValueOnce chains.
  • Describe-level retries (30.5.0) — jest.retryTimes(n, { entireDescribe: true }) retries the whole describe block, not just individual tests. Complements the existing per-test jest.retryTimes.
  • --collectTests expansion (30.5.0) — expands test.each/describe.each cases and reports per-status counts (including wouldRun for skipped tests) plus a summary line matching a real run, also under --testNamePattern and focused describes.
  • Richer retry error output (30.5.0) — nested cause and AggregateError sections render with code frames in retry logs and unhandled-rejection reports.
  • defineConfig / mergeConfig helpers (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() accepts Temporal.Duration; jest.setSystemTime() and useFakeTimers({ now }) accept Temporal.Instant and Temporal.ZonedDateTime; Temporal.Now.* can be faked.
  • Node-native type stripping (30.5.2) — when no transformer claims a .ts, .mts or .cts file, Jest now strips TypeScript types with Node itself.
  • toMatchObject / objectContaining widened (30.5.0) — parameter type is object instead of Record<string, unknown>, so class instances are accepted.

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

이 스킬의 문제 신고