test-code-conventions
БесплатноБез исполняемых скриптовНе проверенPure-reference catalog of test-code conventions: AAA structure (Arrange / Act / Assert), per-test single-responsibility, descriptive naming…
от testland★ 18 звёзд на GitHubОб этом скилле
test-code-conventions
Overview
This skill is a pure reference - no actions, no workflows. It catalogs the test-code conventions a test-code review enforces. When a review flags an issue, this reference gives the reviewer the underlying rule.
When to use
- A new team member is onboarding to the codebase and needs to understand "what we mean by a good test."
- A review flagged an issue and the reviewer needs the underlying rule's rationale.
- The team is authoring its own per-team test conventions document and wants a starting point.
How to use
- Scope to test files. Apply these conventions to
*.spec.*/*.test.*/tests/**only; production code is out of scope. - Read the Act lines first (§1). One scan of the single Act per test tells you what each test exercises before you read the body.
- Check one logical assertion target (§2) and a self-documenting name (§3) - hide the body and see whether the name still explains it.
- Judge the assertions and doubles (§4 assertion specificity, §5 mocking) - loose matchers and behaviour-verification are the common misses.
- Trace fixture scope and magic literals (§6, §7): the smallest scope that holds, and named values across the cause-effect chain.
- Flag slow setup (§10); for E2E tests, apply the selector-priority and web-first rules in §8 / §9.
- Cite the section when flagging. Name the rule (
§4) and spend the words on the specific edit, not on restating the rule.
§1 - AAA structure
The canonical test shape - Arrange, Act, Assert - splits each test into three phases:
test('addItem increases cart count', () => {
// Arrange
const cart = new Cart();
// Act
cart.addItem({ sku: 'BOOK-001', qty: 1 });
// Assert
expect(cart.itemCount).toBe(1);
});
The phases are visually separated (blank line; comment; or
// arrange / act / assert headers). The benefits:
- Reviewer can scan a 50-test file by reading only the Act lines - knows what each test actually exercises.
- Failure debugging is faster: the failed assertion points to the specific Assert; the Arrange and Act are isolated.
Each test has exactly one Act. Two Acts = two tests. Splitting on multiple Acts is the canonical refactor when a single test grows too long.
§2 - Single-responsibility per test
A test that asserts cart.count === 1 AND cart.totalPrice === 10 AND cart.lastUpdated > now() is three tests in disguise. When one
assertion fails, the test stops; the other two failures are
masked.
The rule: one logical assertion per test. "Logical" means
related to the same observable property - multiple expect calls
that all verify "the cart has one item" (count = 1, items.length = 1,
contents[0].sku = '...') are one logical assertion.
Splitting:
// Bad - three logical assertions
test('addItem updates cart', () => {
cart.addItem(...);
expect(cart.itemCount).toBe(1); // assertion 1
expect(cart.totalPrice).toBe(10); // assertion 2 (different property)
expect(cart.lastUpdated).toBeGreaterThan(t0); // assertion 3 (different property)
});
// Good - three tests, each assertion isolated
test('addItem increments count', () => { /* ... */ });
test('addItem updates totalPrice', () => { /* ... */ });
test('addItem updates lastUpdated', () => { /* ... */ });
§3 - Naming patterns
Two well-established conventions:
A - <system_under_test>_<scenario>_<expected> (Roy Osherove)
test('addItem_validQty_incrementsCount', () => { /* ... */ });
test('addItem_zeroQty_throwsValidationError', () => { /* ... */ });
test('addItem_negativeQty_throwsValidationError', () => { /* ... */ });
The triple makes the test self-documenting; no need to read the body to understand what's verified.
B - Nested describe + it
describe('Cart', () => {
describe('addItem', () => {
describe('with valid qty', () => {
it('increments count', () => { /* ... */ });
});
describe('with zero qty', () => {
it('throws ValidationError', () => { /* ... */ });
});
});
});
Both are valid; the team picks one and stays consistent. Mixing the two in one suite is the smell.
Avoid: test('it works'), test('test 1'),
test('addItem 1'), test('addItem 2'). Generic names are zero
debugging help when the failure surfaces.
§4 - Assertion specificity
Assertions should narrow the verification window to exactly what's being asserted. Vague matchers hide regressions:
| Vague | Specific | Why specific is better |
|---|---|---|
expect(x).toBeTruthy() |
expect(x).toEqual({ id: 1, name: 'foo' }) |
"truthy" passes for 1, 'a', {}, [] - many bug shapes pass. |
expect(arr).toBeDefined() |
Установить test-code-conventions в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл test-code-conventions?
Pure-reference catalog of test-code conventions: AAA structure (Arrange / Act / Assert), per-test single-responsibility, descriptive naming (`{sut}_{scenario}_{expected}`), assertion specificity, mocking rationale (state vs behavior, fake vs mock), fixture-coupling rules, the magic-number / hard-coded-string anti-patterns, and step design (§11: FIRST principles, step granularity, the mechanical → page → business abstraction layers, the rule-of-three extraction heuristic, declarative phrasing); the E2E selector-priority, web-first-assertion, and step-grouping conventions live in references/. Use as the shared rule book a test-code review cites back to, or as onboarding for what makes a test code-reviewable; to score a test's quality on weighted axes use test-design-scorecard, and for setup/teardown isolation specifically use test-isolation-patterns.
Как установить скилл test-code-conventions?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл test-code-conventions запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic