Testing Fundamentals
Learn the essential testing strategies that ensure code quality and reliability in software development.
Why Test?
- Catch bugs early - Before they reach production
- Enable refactoring - Change code with confidence
- Document behavior - Tests serve as living documentation
- Improve design - Testable code is often better designed
Types of Testing
Unit Tests
Test individual functions or components in isolation.
javascript
// Example unit test
test('calculateTotal should add tax to subtotal', () => {
const result = calculateTotal(100, 0.08);
expect(result).toBe(108);
});
Characteristics:
Integration Tests
Test how different parts of your system work together.
javascript
// Example integration test
test('user can create and retrieve a post', async () => {
const post = await createPost({ title: 'Test', content: 'Content' });
const retrieved = await getPost(post.id);
expect(retrieved.title).toBe('Test');
});
Characteristics:
End-to-End (E2E) Tests
Test complete user workflows from start to finish.
javascript
// Example E2E test with Playwright
test('user can complete checkout process', async ({ page }) => {
await page.goto('/products');
await page.click('[data-testid="add-to-cart"]');
await page.click('[data-testid="checkout"]');
await expect(page.locator('.success-message')).toBeVisible();
});
Characteristics:
Testing Pyramid
/\
/E2E\ <- Few, slow, expensive
/____\
/ \
/INTEGR.\ <- Some, medium speed
/_________\
/ \
/ UNIT \ <- Many, fast, cheap
/____________\