unit-testing
БесплатноБез исполняемых скриптовНе проверенWrite effective unit tests with Jest, Vitest, or pytest. Covers the test-doubles taxonomy (stub/spy/mock/fake), Arrange-Act-Assert, coverage threshold…
от petrkindlmann★ 317 звёзд на GitHubОб этом скилле
Discovery Questions
Check .agents/qa-project-context.md first — if it exists, use it and skip anything answered there.
- Framework: Jest, Vitest, or pytest? Check
package.jsonorpyproject.toml. The runner decides config keys and mock APIs. - Coverage tooling: Already configured? Look for
jest.config.*,vitest.config.*,.nycrc,[tool.coverage]. Determines whether you add the gate or just tune it. - Mocking strategy: Manual mocks, auto-mocking, or dependency injection? Check for
__mocks__/dirs or DI containers — this sets which doubles you reach for. - Conventions: Co-location (
*.test.tsnext to source) or a__tests__/tests/tree? Match what exists; don't introduce a third location.
Core Principles
1. Test behavior, not implementation. Verify what code does, not how. Refactoring internals should not break tests.
// Bad — implementation detail // Good — observable behavior
expect(svc._cache.size).toBe(3); expect(svc.getUser("abc")).toEqual({ id: "abc", name: "Alice" });
2. Fast, isolated, deterministic. No network/disk/DB. No shared mutable state. No uncontrolled Date.now() or Math.random() — freeze them with fake timers and seeded values.
3. Arrange-Act-Assert. One clear shape per test.
it("should apply discount for orders over $100", () => {
// Arrange
const order = createOrder({ subtotal: 150 });
const svc = new DiscountService(0.1);
// Act
const result = svc.apply(order);
// Assert
expect(result.total).toBe(135);
});
4. One assertion concept per test. Multiple expect calls are fine when they verify the same concept.
5. Descriptive names. "should [behavior] when [condition]", not "test calculateTotal".
Framework-Specific Patterns
The full setup/teardown, mocking, spying, timer, in-source, and monorepo examples for
each runner live in references/patterns.md. Below is what is current and what to
reach for; copy the code from the reference.
Jest
Current is Jest 30.x (30.4.2, May 2026). Jest 30 added --collect-tests,
jest.config.mts support, Temporal-aware fake timers, and clearMocksOnScope. If the
code under test uses the Temporal API or time-zone logic, Jest 30's Temporal-aware fake
timers remove a class of brittle setup.
Reach for: jest.mock() for module boundaries (jest.requireActual for partial mocks),
jest.spyOn() to wrap a real method, jest.Mocked<T> for typed mocks, and
jest.useFakeTimers() for time. See references/patterns.md § Jest.
Vitest
Same API as Jest, Vite-native. Stable: Vitest 4.1.x (June 2026); 5.0.0-beta is
out (beta.3, May 2026). Vitest 4 added coverage.changed (changed-files-only coverage),
mockThrow/mockThrowOnce, and a stable browser mode. Vitest 5 beta removes the
sequential option and requires Node 22 / Vite 6.4 — wait for stable before
adopting. Mock with vi.mock/vi.spyOn; the standout features are in-source testing
(import.meta.vitest) and browser mode for component rendering. See
references/patterns.md § Vitest.
pytest
Use fixtures + conftest.py (with yield for teardown), @pytest.mark.parametrize
for data-driven cases, and monkeypatch for env/attr substitution. Prefer fixtures
over setUp/tearDown methods — fixtures compose and isolate per test. See
references/patterns.md § pytest.
Bun / Deno
bun test (Jest-compatible, no extra config) and deno test (native TS, permission
flags) are reasonable defaults when your runtime is already Bun or Deno. Prefer
Vitest/Jest for Node projects with deeper plugin ecosystems.
Mocking Taxonomy
Pick the simplest double that does the job. Most of the time that is a stub.
| Double | What it does | When to use |
|---|---|---|
| Stub | Returns canned data, no verification | Control a dependency's return value |
| Spy | Wraps real impl, records calls | Verify calls without changing behavior |
| Mock | Replaces impl + records calls | Control return AND verify interaction |
| Fake | Simplified working impl (in-memory DB) | Complex stateful dependencies |
Rule of thumb: prefer stubs over mocks; reserve fakes for stateful dependencies; never call a real external API in a unit test. Only mock the external boundary (network, fi
Установить unit-testing в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл unit-testing?
Write effective unit tests with Jest, Vitest, or pytest. Covers the test-doubles taxonomy (stub/spy/mock/fake), Arrange-Act-Assert, coverage threshold configuration and CI gating, snapshot testing, fake timers, and mutation testing with Stryker/mutmut. Use when: "unit test," "Jest," "Vitest," "pytest," "mock," "coverage threshold," "test doubles," "mutation testing," "fake timers," "snapshot test." Not for: interpreting coverage reports or finding coverage gaps — use coverage-analysis; AI generating the test code for you — use ai-test-generation; auditing existing tests for smells — use ai-qa-review; browser/component rendering assertions — use cypress-automation or visual-testing. Related: coverage-analysis, ci-cd-integration, ai-test-generation, shift-left-testing.
Как установить скилл unit-testing?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл unit-testing запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic