Last Updated: November 21, 2025
Test-Driven Development
TDD methodology and best practices
TDD Cycle (Red-Green-Refactor)
- Red: Write a failing test first
- Green: Write minimal code to pass the test
- Refactor: Improve code while keeping tests passing
- Repeat for each new feature
TDD Benefits
- Better code design and architecture
- Comprehensive test coverage
- Documentation through tests
- Confidence to refactor
- Fewer bugs in production
- Faster debugging
- Forces you to think about requirements
Test Structure (AAA)
test('should add two numbers', () => {
// Arrange - Set up test data
const a = 5;
const b = 3;
const calculator = new Calculator();
// Act - Execute the code being tested
const result = calculator.add(a, b);
// Assert - Verify the result
expect(result).toBe(8);
});
Best Practices
- Write one test at a time
- Keep tests simple and focused
- Test behavior, not implementation
- Use descriptive test names
- Follow the Arrange-Act-Assert pattern
- Make tests independent (no shared state)
- Test edge cases and error conditions
- Keep test code clean too
Common Testing Patterns
| Item | Description |
|---|---|
Unit Tests
|
Test individual functions/classes |
Integration Tests
|
Test component interactions |
Mocking
|
Replace dependencies with fake objects |
Stubbing
|
Return predetermined values |
Test Fixtures
|
Set up consistent test state |
Parameterized Tests
|
Run same test with different inputs |
💡 Pro Tips
Quick Reference
Write tests before code for better quality