
testing-patterns
by gtakairo
Personal dotfiles and development environment configurations with comprehensive Claude Code setup
SKILL.md
name: testing-patterns description: "Testing best practices and TDD workflow. Use when writing tests, following TDD, or improving test coverage." enabled: true visibility: default allowedTools: ["bash", "read", "write", "edit"]
Testing Patterns Skill
Implement comprehensive testing strategies following TDD principles and best practices.
Testing Philosophy
Test-Driven Development (TDD) Cycle
- Red: Write a failing test
- Green: Write minimal code to pass
- Refactor: Improve code while keeping tests passing
Testing Pyramid
/\
/E2E\ <- Few (Slow, Expensive)
/------\
/Integration\ <- Some (Medium Speed/Cost)
/------------\
/ Unit Tests \ <- Many (Fast, Cheap)
/----------------\
Test Categories
1. Unit Tests
Purpose: Test individual functions/methods in isolation
Characteristics:
- Fast execution (< 100ms each)
- No external dependencies (mock/stub)
- Test one thing at a time
- Independent and repeatable
Example Structure:
describe('functionName', () => {
it('should handle valid input', () => {
// Arrange
const input = 'test';
// Act
const result = functionName(input);
// Assert
expect(result).toBe('expected');
});
it('should throw on invalid input', () => {
expect(() => functionName(null))
.toThrow('Invalid input');
});
});
2. Integration Tests
Purpose: Test component interactions
Characteristics:
- Test multiple units together
- May use test database/APIs
- Verify data flow between components
- Slower than unit tests
3. End-to-End Tests
Purpose: Test complete user workflows
Characteristics:
- Simulate real user behavior
- Test full stack integration
- Slowest but highest confidence
- Use sparingly for critical paths
Best Practices
Test Structure (AAA Pattern)
// Arrange: Set up test data and conditions
// Act: Execute the function/method
// Assert: Verify the expected outcome
Naming Conventions
- Test file:
{filename}.test.jsor{filename}.spec.js - Test name:
should [expected behavior] when [condition] - Descriptive and readable
What to Test
✅ Do Test:
- Public API/interface
- Edge cases and boundaries
- Error conditions
- Business logic
- State changes
❌ Don't Test:
- Implementation details
- Third-party library internals
- Private methods (test through public API)
- Trivial code (getters/setters)
Test Coverage Goals
- Critical paths: 100%
- Business logic: 90%+
- Overall: 80%+ (but quality > quantity)
- Focus on meaningful coverage, not just metrics
Common Testing Patterns
1. Mock External Dependencies
// Mock API calls
jest.mock('./api', () => ({
fetchData: jest.fn(() => Promise.resolve({ data: 'mock' }))
}));
2. Test Async Code
it('should fetch data', async () => {
const data = await fetchData();
expect(data).toBeDefined();
});
3. Parameterized Tests
describe.each([
[1, 2, 3],
[2, 3, 5],
[5, 5, 10]
])('add(%i, %i)', (a, b, expected) => {
it(`should return ${expected}`, () => {
expect(add(a, b)).toBe(expected);
});
});
4. Setup/Teardown
beforeEach(() => {
// Setup before each test
database.connect();
});
afterEach(() => {
// Cleanup after each test
database.disconnect();
});
Test Smells to Avoid
🚫 Flaky Tests: Tests that randomly fail
- Fix: Remove race conditions, use proper async/await
🚫 Slow Tests: Unit tests taking seconds
- Fix: Mock external dependencies
🚫 Test Interdependence: Tests relying on order
- Fix: Make tests independent
🚫 Overly Specific Assertions: Testing implementation
- Fix: Test behavior, not implementation
🚫 Missing Edge Cases: Only testing happy path
- Fix: Add boundary and error tests
Testing Checklist
Before completing testing:
- All new code has tests
- Edge cases covered
- Error conditions tested
- Tests are fast and independent
- Mock external dependencies
- Tests have clear names
- Coverage meets project standards
- Tests pass consistently
- No flaky tests
Language-Specific Tips
JavaScript/TypeScript
- Use Jest, Vitest, or Mocha
- Mock with
jest.fn()orvi.fn() - Test async with
async/await
Python
- Use pytest or unittest
- Mock with
unittest.mockorpytest-mock - Use fixtures for setup
Bash/Shell
- Use
bats(Bash Automated Testing System) - Test exit codes and output
- Mock commands with functions
Example: TDD Workflow
# 1. Write failing test
# test_calculator.py
def test_add():
assert add(2, 3) == 5 # Fails: add() not defined
# 2. Write minimal code
# calculator.py
def add(a, b):
return a + b # Now test passes
# 3. Refactor if needed
def add(a: int, b: int) -> int:
"""Add two integers."""
return a + b
# 4. Add more tests
def test_add_negative():
assert add(-1, 1) == 0
Resources
- Write tests first (TDD)
- Keep tests simple and focused
- Test behavior, not implementation
- Maintain tests like production code
- Run tests frequently (CI/CD)
スコア
総合スコア
リポジトリの品質指標に基づく評価
SKILL.mdファイルが含まれている
ライセンスが設定されている
100文字以上の説明がある
GitHub Stars 100以上
3ヶ月以内に更新がある
10回以上フォークされている
オープンIssueが50未満
プログラミング言語が設定されている
1つ以上のタグが設定されている
レビュー
レビュー機能は近日公開予定です