Frontend Testing
Frontend Testing
Phần tiêu đề “Frontend Testing”Chiến lược testing cho frontend apps.
Testing Pyramid
Phần tiêu đề “Testing Pyramid” /\ /E2E\ ← Ít tests, chậm, đắt /------\ /Integration\ ← Vừa phải /------------\ / Unit Tests \ ← Nhiều tests, nhanh, rẻ /----------------\Unit Tests (Vitest/Jest)
Phần tiêu đề “Unit Tests (Vitest/Jest)”export function sum(a, b) { return a + b;}
// sum.test.jsimport { expect, test } from "vitest";import { sum } from "./sum";
test("adds 1 + 2 to equal 3", () => { expect(sum(1, 2)).toBe(3);});Component Tests (React Testing Library)
Phần tiêu đề “Component Tests (React Testing Library)”import { render, screen, fireEvent } from "@testing-library/react";import Counter from "./Counter";
test("increments counter", () => { render(<Counter />);
const button = screen.getByText(/increment/i); fireEvent.click(button);
expect(screen.getByText(/count: 1/i)).toBeInTheDocument();});E2E Tests (Playwright/Cypress)
Phần tiêu đề “E2E Tests (Playwright/Cypress)”// Playwrighttest("user can login", async ({ page }) => { await page.goto("http://localhost:3000"); await page.fill('input[name="email"]', "test@example.com"); await page.fill('input[name="password"]', "password"); await page.click('button[type="submit"]');
await expect(page.locator("text=Welcome")).toBeVisible();});Best Practices
Phần tiêu đề “Best Practices”- Test behavior, not implementation
- AAA pattern: Arrange, Act, Assert
- Write meaningful test descriptions
- Mock external dependencies
- Keep tests simple and focused