Yasin Avci

Yasin Avci

Full-Stack Developer

Paris, France

Contact me
Back to articles
TestingQualityDevOps

Automated Tests: The Strategy That Prevents Regressions

Unit tests, integration, E2E... How to build an effective test pyramid without wasting time.

April 10, 20244 min read

"It was working before the production deployment." I've heard this phrase too many times. The solution? A testing strategy adapted to your project.

The Test Pyramid

Fundamental concept: the higher a test is in the pyramid, the slower and more costly it is to maintain.

        /\
       /  \     E2E (few, critical)
      /----\
     /      \   Integration (moderate)
    /--------\
   /          \ Unit (many)
  --------------

Unit Tests: The Solid Foundation

Test a function or component in isolation, without external dependencies.

// utils/formatPrice.test.ts
import { formatPrice } from './formatPrice';

describe('formatPrice', () => {
  it('formats a price in dollars', () => {
    expect(formatPrice(1234.5)).toBe('$1,234.50');
  });

  it('handles zero prices', () => {
    expect(formatPrice(0)).toBe('$0.00');
  });

  it('rounds correctly', () => {
    expect(formatPrice(10.999)).toBe('$11.00');
  });
});

Characteristics:

  • Instant execution (< 10ms per test)
  • Easy to write and maintain
  • Immediate feedback during development

What to test: utility functions, business logic, data transformations.

Integration Tests: The Connections

Verify that multiple modules work together.

// api/users.test.ts
import { createUser, getUser } from './users';
import { db } from './database';

beforeEach(async () => {
  await db.clear();
});

describe('User API', () => {
  it('creates and retrieves a user', async () => {
    const created = await createUser({
      email: 'test@example.com',
      name: 'Test User'
    });

    const retrieved = await getUser(created.id);

    expect(retrieved.email).toBe('test@example.com');
  });
});

Characteristics:

  • Slower (database access, network)
  • Detect interface problems between modules
  • Require a test environment

What to test: API routes, database interactions, mocked external services.

E2E Tests: The User Journey

Simulate a real user interacting with the application.

// e2e/checkout.spec.ts
import { test, expect } from '@playwright/test';

test('complete purchase journey', async ({ page }) => {
  // Add a product to cart
  await page.goto('/products/123');
  await page.click('button:text("Add to cart")');

  // Go to checkout
  await page.click('a:text("View cart")');
  await page.click('button:text("Checkout")');

  // Fill in information
  await page.fill('[name="email"]', 'customer@example.com');
  await page.fill('[name="address"]', '123 Example Street');
  await page.click('button:text("Pay")');

  // Verify confirmation
  await expect(page.locator('h1')).toContainText('Order confirmed');
});

Characteristics:

  • Slow (several seconds per test)
  • Fragile (sensitive to UI changes)
  • High confidence (test the complete system)

What to test: critical journeys (registration, purchase, key features).

My Strategy in Practice

Recommended Ratio

| Type | Proportion | Execution Time | |------|------------|----------------| | Unit | 70% | < 30 seconds | | Integration | 20% | < 2 minutes | | E2E | 10% | < 10 minutes |

When to Write Tests?

  1. Before coding (TDD): for complex business logic
  2. After a bug: the test prevents regression
  3. For critical journeys: what loses money if it breaks

When NOT to Write Tests?

  • Throwaway prototypes
  • UI code that changes constantly
  • Trivial wrappers without logic

Recommended Tools

For React/Next.js

{
  "devDependencies": {
    "vitest": "^1.0.0",
    "@testing-library/react": "^14.0.0",
    "playwright": "^1.40.0"
  }
}
  • Vitest: fast, Jest compatible, efficient watch mode
  • Testing Library: tests oriented toward user behavior
  • Playwright: reliable E2E, multi-browser

File Structure

src/
  components/
    Button/
      Button.tsx
      Button.test.tsx    # Unit tests
  lib/
    api/
      users.ts
      users.test.ts      # Integration tests
e2e/
  checkout.spec.ts       # E2E tests
  auth.spec.ts

CI/CD Integration

# .github/workflows/test.yml
name: Tests
on: [push, pull_request]

jobs:
  unit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: pnpm install
      - run: pnpm test:unit

  e2e:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: pnpm install
      - run: pnpm build
      - run: pnpm test:e2e

Unit tests block the merge immediately. E2E runs in parallel.

Pitfalls to Avoid

  1. Testing implementation, not behavior

    // ❌ Fragile: tests internal details
    expect(component.state.isLoading).toBe(true);
    
    // âś… Robust: tests what user sees
    expect(screen.getByText('Loading...')).toBeInTheDocument();
    
  2. Tests too coupled to data

    // ❌ Breaks if ID changes
    expect(user.id).toBe(123);
    
    // âś… Verifies structure
    expect(user).toHaveProperty('id');
    
  3. 100% coverage as a goal

    Coverage measures lines executed, not assertion quality. 80% relevant coverage is worth more than 100% superficial tests.

Conclusion

A good testing strategy isn't about having the most tests possible, but the right tests in the right places.

Start small: a few unit tests on critical logic, one E2E test on the main journey. Add tests when you fix bugs. In a few months, you'll have a solid safety net.