Netestovaný kód je nespoľahlivý kód. Testy sú investícia, ktorá šetrí čas a peniaze v dlhodobom horizonte.

Testovacia pyramída

        /\
       /E2E\
      /------\
     /Integration\
    /--------------\
   /   Unit Tests   \
  /------------------\

Viac unit testov, menej E2E - unit testy sú rýchle a lacné.

Unit testy

Testujú jednotlivé funkcie izolovane.

// math.ts
export function add(a: number, b: number): number {
  return a + b
}

// math.test.ts
import { add } from './math'

describe('add', () => {
  it('should add two positive numbers', () => {
    expect(add(2, 3)).toBe(5)
  })

  it('should handle negative numbers', () => {
    expect(add(-1, 1)).toBe(0)
  })
})

Best practices

  • Testujte jednu vec na test
  • Používajte deskriptívne názvy
  • AAA pattern: Arrange, Act, Assert

Integračné testy

Testujú spoluprácu viacerých častí.

// api.test.ts
describe('User API', () => {
  it('should create and retrieve user', async () => {
    // Arrange
    const userData = { name: 'John', email: 'john@example.com' }

    // Act
    const created = await api.post('/users', userData)
    const retrieved = await api.get(`/users/${created.id}`)

    // Assert
    expect(retrieved.name).toBe(userData.name)
  })
})

E2E testy

Testujú celú aplikáciu z pohľadu používateľa.

// Playwright example
import { test, expect } from '@playwright/test'

test('user can login', async ({ page }) => {
  await page.goto('/login')
  await page.fill('[name="email"]', 'user@example.com')
  await page.fill('[name="password"]', 'password123')
  await page.click('button[type="submit"]')

  await expect(page).toHaveURL('/dashboard')
  await expect(page.locator('.welcome')).toContainText('Welcome')
})

Nástroje

Typ JavaScript Python
Unit Jest, Vitest pytest
Integration Supertest pytest
E2E Playwright, Cypress Playwright, Selenium

Code coverage

vitest --coverage

Cieľ nie je 100% - sústreďte sa na kritické cesty.

TDD (Test-Driven Development)

  1. Napíšte test (červený)
  2. Napíšte minimálny kód pre úspech (zelený)
  3. Refaktorujte (refactor)

Záver

Začnite s unit testami pre kritickú business logiku. Pridajte integračné testy pre API. E2E testy pre hlavné user flows. Testujte pravidelne v CI/CD.