testing
TDD patterns, test writing strategies, coverage guidance, mocking patterns. Use when: write tests, TDD, test coverage, unit test, integration test, E2E test, mocking, test organization, pytest, vitest, jest.
What this skill does
<objective>
Comprehensive testing skill covering TDD workflow, test pyramid strategy, mocking patterns, and coverage guidance. Framework-agnostic patterns applicable to pytest, vitest, jest, and other testing frameworks.
This skill emphasizes writing tests that provide confidence without becoming maintenance burdens. Tests should be fast, reliable, and focused on behavior rather than implementation details.
</objective>
<quick_start>
**TDD Red-Green-Refactor cycle:**
1. **RED**: Write a failing test first
```typescript
test('adds numbers', () => {
expect(add(1, 2)).toBe(3); // Fails - add() doesn't exist
});
```
2. **GREEN**: Write minimum code to pass
```typescript
const add = (a, b) => a + b; // Test passes
```
3. **REFACTOR**: Clean up while tests stay green
**Test pyramid**: 70% unit, 25% integration, 5% E2E
</quick_start>
<success_criteria>
Testing is successful when:
- TDD cycle followed: test written before implementation code
- Test pyramid balanced: ~70% unit, ~25% integration, ~5% E2E
- Tests are independent and can run in any order
- No flaky tests (run 3x to verify reliability)
- Coverage meets targets: 70-80% lines, 100% critical paths
- Test names describe behavior (what + when + expected result)
- Mocks only used for external dependencies, not own code
</success_criteria>
<core_principles>
## The Testing Mindset
1. **Tests are documentation** - A failing test is a specification that hasn't been implemented
2. **Test behavior, not implementation** - Tests should survive refactoring
3. **Fast feedback loops** - Unit tests run in milliseconds, not seconds
4. **Isolation by default** - Each test should be independent
5. **Arrange-Act-Assert** - Clear structure in every test
</core_principles>
<tdd_workflow>
## TDD: Red-Green-Refactor
```
┌─────────────────────────────────────────────────────────┐
│ TDD CYCLE │
│ │
│ ┌─────────┐ │
│ │ RED │ ◄─── Write a failing test │
│ └────┬────┘ │
│ │ │
│ ▼ │
│ ┌─────────┐ │
│ │ GREEN │ ◄─── Write minimum code to pass │
│ └────┬────┘ │
│ │ │
│ ▼ │
│ ┌─────────┐ │
│ │REFACTOR │ ◄─── Clean up while tests stay green │
│ └────┬────┘ │
│ │ │
│ └──────────────► Back to RED │
└─────────────────────────────────────────────────────────┘
```
### The Rules
1. **Write a failing test first** - Never write production code without a failing test
2. **Write only enough test to fail** - Compilation failures count as failures
3. **Write only enough code to pass** - No more, no less
4. **Refactor only when green** - Never refactor with failing tests
### Common TDD Mistakes
| Mistake | Why It's Wrong | Instead |
|---------|----------------|---------|
| Writing tests after code | Tests become confirmation bias | Red-Green-Refactor |
| Testing private methods | Tests implementation, not behavior | Test public interface |
| Big leaps in test complexity | Hard to debug failures | Baby steps |
| Skipping refactor step | Technical debt accumulates | Always clean up |
</tdd_workflow>
<test_pyramid>
## The Test Pyramid
```
┌───────────┐
│ E2E │ Few, slow, expensive
│ Tests │ (minutes)
└─────┬─────┘
│
┌──────────┴──────────┐
│ Integration Tests │ Some, medium speed
│ (API, Database) │ (seconds)
└──────────┬───────────┘
│
┌─────────────────┴─────────────────┐
│ Unit Tests │ Many, fast, cheap
│ (Functions, Components) │ (milliseconds)
└────────────────────────────────────┘
```
### Distribution Guidelines
| Type | Percentage | Speed | Scope |
|------|------------|-------|-------|
| Unit | 70-80% | <10ms each | Single function/component |
| Integration | 15-25% | <1s each | Multiple components, DB |
| E2E | 5-10% | <30s each | Full user flows |
### What to Test Where
**Unit Tests:**
- Pure functions
- Business logic
- Data transformations
- Validation rules
- Component rendering
**Integration Tests:**
- API endpoints
- Database operations
- Service interactions
- Component integration
**E2E Tests:**
- Critical user flows (login, checkout)
- Happy paths only
- Smoke tests
</test_pyramid>
<when_to_mock>
## Mocking Strategy
### The London vs Detroit Schools
**London School (Mockist):**
- Mock all dependencies
- Test in complete isolation
- Tests are very focused
**Detroit School (Classicist):**
- Only mock external services
- Test natural units together
- Tests are more realistic
**Recommended: Pragmatic approach**
- Mock external services (APIs, DBs in unit tests)
- Don't mock your own code unless necessary
- Use real implementations in integration tests
### What to Mock
| Mock | Don't Mock |
|------|------------|
| External APIs | Your own pure functions |
| File system (in unit tests) | Data transformations |
| Network requests | Business logic |
| Time/randomness | In-memory data structures |
| Expensive computations | Simple utilities |
### Mocking Patterns
```typescript
// GOOD: Mock external dependency
const mockFetch = vi.fn().mockResolvedValue({ data: [] });
// BAD: Mocking your own utilities
const mockFormatDate = vi.fn(); // Don't do this
// GOOD: Dependency injection for testability
function createService(httpClient = fetch) {
return {
getData: () => httpClient('/api/data')
};
}
// In test:
const mockClient = vi.fn();
const service = createService(mockClient);
```
</when_to_mock>
<test_structure>
## Test Organization
### File Naming
```
src/
├── components/
│ ├── Button.tsx
│ └── Button.test.tsx # Colocated test
├── utils/
│ ├── format.ts
│ └── format.test.ts
└── __tests__/ # Or separate folder
└── integration/
└── api.test.ts
```
### Test Naming
```typescript
// Pattern: describe what + when + expected result
describe('UserService', () => {
describe('createUser', () => {
it('returns user object when given valid email', () => {});
it('throws ValidationError when email is invalid', () => {});
it('sends welcome email after successful creation', () => {});
});
});
// Alternative: BDD style
describe('UserService', () => {
describe('when creating a user with valid data', () => {
it('should return the created user', () => {});
it('should send a welcome email', () => {});
});
describe('when email is invalid', () => {
it('should throw ValidationError', () => {});
});
});
```
### Arrange-Act-Assert
```typescript
it('calculates total with discount', () => {
// Arrange - set up test data
const cart = createCart([
{ price: 100, quantity: 2 },
{ price: 50, quantity: 1 }
]);
const discount = 0.1;
// Act - perform the action
const total = calculateTotal(cart, discount);
// Assert - verify result
expect(total).toBe(225); // (200 + 50) * 0.9
});
```
</test_structure>
<what_not_to_test>
## What NOT to Test
### Skip These
1. **Framework code** - React's useState, Express routing
2. **Third-party libraries** - They have their own tests
3. **Trivial getters/setters** - No logic = no test needed
4. **Implementation details** - Private methods, internal state
5. **One-line functions** - UnlRelated in Writing & Docs
jax-development
IncludedUse this skill when the user is writing, debugging, profiling, refactoring, reviewing, benchmarking, parallelising, exporting, or explaining JAX code, or when they mention JAX, jax.numpy, jit, grad, value_and_grad, vmap, scan, lax, random keys, pytrees, jax.Array, sharding, Mesh, PartitionSpec, NamedSharding, pmap, shard_map, Pallas, XLA, StableHLO, checkify, profiler, or the JAX repo. It helps turn NumPy or PyTorch-style code into pure functional JAX, fix tracer/control-flow/shape/PRNG bugs, remove recompiles and host-device syncs, choose transforms and sharding strategies, inspect jaxpr/lowering/IR, and benchmark compiled code correctly.
nature-article-writer
IncludedDrafts, rewrites, diagnostically critiques, and style-calibrates primary research manuscripts for Nature and Nature Portfolio journals. Use when the user wants a Nature-style title, summary paragraph or abstract, introduction, results, discussion, methods, figure legends, presubmission enquiry, cover letter, reviewer response, or when a scientific draft sounds generic, jargon-heavy, structurally weak, or AI-ish and needs precise, broad-reader-friendly prose without inventing data, analyses, or references. Best for primary research articles and letters rather than reviews or press releases unless explicitly adapting one.
deckrd
IncludedDocument-driven framework that derives requirements, specifications, implementation plans, and executable tasks from goals through structured AI dialogue. Use when user says "write requirements", "create spec", "plan implementation", "derive tasks", "structure this feature", "break down into tasks", or "document this module". Also use for reverse engineering existing code into docs (/deckrd rev). Do NOT use for direct code writing — use /deckrd-coder after tasks are generated. Do NOT use when the user only wants to run or fix existing code without planning.
clinical-decision-support
IncludedGenerate professional clinical decision support (CDS) documents for pharmaceutical and clinical research settings, including patient cohort analyses (biomarker-stratified with outcomes) and treatment recommendation reports (evidence-based guidelines with decision algorithms). Supports GRADE evidence grading, statistical analysis (hazard ratios, survival curves, waterfall plots), biomarker integration, and regulatory compliance. Outputs publication-ready LaTeX/PDF format optimized for drug development, clinical research, and evidence synthesis.
handling-sf-data
IncludedSalesforce data operations with 130-point scoring. Use this skill to create, update, delete, bulk import/export, generate test data, and clean up org records using sf CLI and anonymous Apex. TRIGGER when: user creates test data, performs bulk import/export, uses sf data CLI commands, needs data factory patterns for Apex tests, or needs to seed/clean records in a Salesforce org. DO NOT TRIGGER when: SOQL query writing only (use querying-soql), Apex test execution (use running-apex-tests), or metadata deployment (use deploying-metadata).
accelint-ac-to-playwright
IncludedConvert and validate acceptance criteria for Playwright test automation. Use when user asks to (1) review/evaluate/check if AC are ready for automation, (2) assess if AC can be converted as-is, (3) validate AC quality for Playwright, (4) turn AC into tests, (5) generate tests from acceptance criteria, (6) convert .md bullets or .feature Gherkin files to Playwright specs, (7) create test automation from requirements. Handles both bullet-style markdown and Gherkin syntax with JSON test plan generation and validation.