Skip to main content
testing-unit Unit testing patterns for isolated business logic tests — AAA pattern, parametrized tests (test.each, @pytest.mark.parametrize), fixture scoping (function/module/session), mocking with MSW/VCR at network level, and test data management with factories (FactoryBoy, faker-js). Use when writing unit tests, setting up mocks, structuring test data, optimizing test speed, choosing fixture scope, or reducing test boilerplate. Covers Vitest, Jest, pytest.
الانتقال إلى التثبيت سوق المهارات اكتشف واستكشف مهارات الذكاء الاصطناعي التي بناها المجتمع.
التثبيت باستخدام Codex أو Claude انسخ هذا Prompt والصقه في Codex أو Claude أو مساعد آخر ليراجع صفحة Skill ويثبّتها لك.
نسخ Promptعرض تفاصيل Prompt يتجاوز الأمر المباشر Prompt المخصّص للمراجعة. افحص المصدر قبل تشغيله.
npx skills add https://github.com/yonatangross/orchestkit --skill testing-unitيبقى الأمر في سطر واحد. مرّر أفقيًا لمراجعته كاملًا قبل النسخ.
تفضّل نسخة محلية؟ نزّل الملفات المتاحة حاليًا لدى SkillsMP.
تحميل Zip جاري التحميل... المهن ذات الصلة SOC
استنادا إلى تصنيف SOC المهني
name testing-unit license MIT compatibility Claude Code 2.1.220+. description Unit testing patterns for isolated business logic tests — AAA pattern, parametrized tests (test.each, @pytest.mark.parametrize), fixture scoping (function/module/session), mocking with MSW/VCR at network level, and test data management with factories (FactoryBoy, faker-js). Use when writing unit tests, setting up mocks, structuring test data, optimizing test speed, choosing fixture scope, or reducing test boilerplate. Covers Vitest, Jest, pytest. tags ["testing","unit","mocking","msw","vcr","fixtures","factories","vitest-4","aroundEach"] context fork agent test-generator version 2.1.0 author OrchestKit user-invocable false disable-model-invocation false complexity medium persuasion-type reference targets [{"library":"vitest","version":">=4.1.0"}] metadata {"category":"document-asset-creation"} allowed-tools ["Read","Glob","Grep","WebFetch","WebSearch"] path_patterns ["*.test.*","*.spec.*","**/vitest.config.*","**/jest.config.*"]
Unit Testing Patterns
Focused patterns for writing isolated, fast, maintainable unit tests. Covers test structure (AAA), parametrization, fixture management, HTTP mocking (MSW/VCR), and test data generation with factories.
Each category has individual rule files in rules/ loaded on-demand, plus reference material, checklists, and scaffolding scripts.
Core Principles (ALWAYS apply)
AAA structure : Every test MUST follow Arrange-Act-Assert. Use // Arrange, // Act, // Assert comments for clarity.
Parametrize, don't duplicate : Use test.each (TypeScript) or @pytest.mark.parametrize (Python) when testing multiple inputs. Never copy-paste the same test body with different values.
Fixture scoping matters : Use scope="function" (default) for mutable data. Use scope="module" or scope="session" ONLY for expensive read-only resources (DB engines, ML models). Mutable data with shared scope causes flaky tests.
Speed target : Each unit test should run under 100ms . If it's slower, you're likely hitting I/O — mock it.
Mock at the network level : Use MSW (TypeScript) or VCR.py (Python) to intercept HTTP at the network layer. Never mock fetch/axios/requests directly.
Quick Reference
Total: 8 rules across 3 categories, 4 references, 3 checklists, 1 example set, 3 scripts
Unit Test Structure
Core patterns for structuring isolated unit tests with clear phases and efficient execution.
AAA Pattern rules/unit-aaa-pattern.mdArrange-Act-Assert with isolation Fixture Scoping rules/unit-fixture-scoping.mdfunction/module/session scope selection Parametrized Tests rules/unit-parametrized.mdtest.each / @pytest.mark.parametrize
Reference: references/aaa-pattern.md — detailed AAA implementation with checklist
HTTP Mocking Network-level request interception for deterministic tests without hitting real APIs.
Rule File Key Pattern MSW 2.x rules/mocking-msw.mdNetwork-level mocking for frontend (TypeScript) VCR.py rules/mocking-vcr.mdRecord/replay HTTP cassettes (Python)
references/msw-2x-api.md — full MSW 2.x API (handlers, GraphQL, WebSocket, passthrough)
references/stateful-testing.md — Hypothesis RuleBasedStateMachine for stateful tests
checklists/msw-setup-checklist.md — MSW installation, handler setup, test writing
checklists/vcr-checklist.md — VCR configuration, sensitive data filtering, CI setup
Examples: examples/handler-patterns.md — CRUD, error simulation, auth flow, file upload handlers
Test Data Management Factories, fixtures, and seeding patterns for isolated, realistic test data.
Rule File Key Pattern Data Factories rules/data-factories.mdFactoryBoy / @faker-js builders Data Fixtures rules/data-fixtures.mdJSON fixtures with composition Seeding & Cleanup rules/data-seeding-cleanup.mdAutomated DB seeding and teardown
Reference: references/factory-patterns.md — advanced factory patterns (Sequence, SubFactory, Traits)
Checklist: checklists/test-data-checklist.md — data generation, cleanup, isolation verification
Quick Start
TypeScript (Vitest + MSW) import { describe, test, expect, beforeAll, afterEach, afterAll } from 'vitest' ;
import { http, HttpResponse } from 'msw' ;
import { setupServer } from 'msw/node' ;
import { calculateDiscount } from './pricing' ;
describe ('calculateDiscount' , () => {
test.each ([
[100 , 0 ],
[150 , 15 ],
[200 , 20 ],
])('for order $%i returns $%i discount' , (total, expected ) => {
const order = { total };
const discount = calculateDiscount (order);
expect (discount).toBe (expected);
});
});
const server = setupServer (
http.get ('/api/users/:id' , ({ params } ) => {
return HttpResponse .json ({ id : params.id , name : 'Test User' });
})
);
beforeAll (() => server.listen ({ onUnhandledRequest : 'error' }));
afterEach (() => server.resetHandlers ());
afterAll (() => server.close ());
test ('fetches user from API' , async () => {
const response = await fetch ('/api/users/123' );
const data = await response.json ();
expect (data.name ).toBe ('Test User' );
});
Python (pytest + FactoryBoy) import pytest
from factory import Factory, Faker, SubFactory
class UserFactory (Factory ):
class Meta :
model = dict
email = Faker('email' )
name = Faker('name' )
class TestUserService :
@pytest.mark.parametrize("role,can_edit" , [
("admin" , True ),
("viewer" , False ),
] )
def test_edit_permission (self, role, can_edit ):
user = UserFactory(role=role)
result = user_can_edit(user)
assert result == can_edit
Vitest 4.1 Features
aroundEach / aroundAll (preferred for DB transactions) Wraps each test in setup/teardown — cleaner than separate beforeEach/afterEach for transactions:
test.aroundEach (async (runTest, { db }) => {
await db.transaction (runTest)
})
test ('insert user' , async ({ db }) => {
await db.insert ({ name : 'Alice' })
})
aroundAll wraps entire suites the same way.
mockThrow / mockThrowOnce Replaces the verbose mockImplementation(() => { throw err }) pattern:
const fn = vi.fn ()
fn.mockThrow (new Error ('connection lost' ))
fn.mockThrowOnce (new Error ('timeout' ))
vi.defineHelper (clean stack traces) Custom assertion helpers that point errors to the call site, not the helper internals:
const assertPair = vi.defineHelper ((a, b ) => {
expect (a).toEqual (b)
})
Test Tags Filter tests by tags in CLI — useful for CI fast paths:
test : {
tags : {
unit : { timeout : 5000 },
flaky : { retry : 3 },
}
}
vitest --tags-filter="unit and !flaky"
vitest --tags-filter="(unit or integration) and !slow"
Agent Reporter Minimal output (failures only) — use in AI agent / CI contexts:
Key Decisions Decision Recommendation Test framework (TS) Vitest 4.1+ (modern, fast, aroundEach, test tags) or Jest (mature ecosystem) Test framework (Python) pytest with plugins (parametrize, asyncio, cov) HTTP mocking (TS) MSW 2.x at network level, never mock fetch/axios directly HTTP mocking (Python) VCR.py with cassettes, filter sensitive data Test data Factories (FactoryBoy/faker-js) over hardcoded fixtures Fixture scope scope="function" for mutable (default). module/session ONLY for expensive immutable resourcesExecution time Under 100ms per unit test — if slower, mock external calls Coverage target 90%+ business logic, 100% critical paths
Common Mistakes
Testing implementation details instead of public behavior (brittle tests)
Mocking fetch/axios directly instead of using MSW at network level (incomplete coverage)
Shared mutable state between tests via module-scoped fixtures (flaky tests)
Hard-coded test data with duplicate IDs (test conflicts in parallel runs)
No cleanup after database seeding (state leaks between tests)
Over-mocking — testing your mocks instead of your code (false confidence)
Verbose throw mocking — mockImplementation(() => { throw err }) instead of mockThrow(err) (Vitest 4.1+)
Scripts Script File Purpose Create Test Case scripts/create-test-case.mdScaffold test file with auto-detected framework Create Test Fixture scripts/create-test-fixture.mdScaffold pytest fixture with context detection Create MSW Handler scripts/create-msw-handler.mdScaffold MSW handler for an API endpoint
OrchestKit doctor for health diagnostics across manifest integrity, hook configuration, skill validation, agent frontmatter, MCP server connectivity, CC version compatibility, and permission rules. Reports issues with severity levels and auto-remediation suggestions. Validates component counts, detects orphaned entries, and checks CC version matrix compliance. Use when diagnosing plugin health, troubleshooting configuration issues, or running pre-release checks.