Testing
สามชั้น สามเครื่องมือ
หัวข้อที่มีชื่อว่า “สามชั้น สามเครื่องมือ”การ test แอป Svelte คือ pyramid เดียวกับ frontend ทั่วไป โดยมี helper ที่รู้จัก Svelte ตรงชั้น component:
| ชั้น | เครื่องมือ | ครอบคลุมอะไร |
|---|---|---|
| Unit | Vitest | logic ล้วน, utility และ runed .svelte.js module |
| Component | @testing-library/svelte + Vitest | component ที่ render ใน jsdom — behaviour ไม่ใช่ internals |
| End-to-end | Playwright | แอปจริงใน browser จริง ข้ามหลายหน้า |
flowchart TB e2e["Playwright: end-to-end (few)"] --> comp["Testing Library: components (some)"] comp --> unit["Vitest: logic + runed modules (many)"]
unit test ด้วย Vitest
หัวข้อที่มีชื่อว่า “unit test ด้วย Vitest”logic ล้วน ๆ — formatter, การคำนวณ, ฟังก์ชัน update ของ store — ทดสอบด้วย Vitest ที่ใช้ config ร่วมกับ Vite จึงเข้าใจโปรเจกต์คุณตั้งแต่แรก:
import { describe, it, expect } from 'vitest';import { formatPrice } from './money';
describe('formatPrice', () => { it('adds a currency symbol', () => { expect(formatPrice(5)).toBe('$5.00'); });});reactive state ใน module .svelte.js / .svelte.ts (rune นอก component) ทดสอบด้วยวิธีเดียวกัน — Vitest รันด้วย Svelte plugin ให้ rune ทำงานใน test ห่อ assertion ที่ขึ้นกับ effect ด้วย $effect.root หรือ flush ด้วย await tick() เมื่อจำเป็น
component test ด้วย Testing Library
หัวข้อที่มีชื่อว่า “component test ด้วย Testing Library”@testing-library/svelte render component เข้า jsdom แล้วให้ query และ interaction ที่สะท้อนพฤติกรรมผู้ใช้ — query ด้วย role/text ไม่ใช่ชื่อ class ภายใน:
import { render, screen } from '@testing-library/svelte';import userEvent from '@testing-library/user-event';import { expect, test } from 'vitest';import Counter from './Counter.svelte';
test('increments on click', async () => { render(Counter, { props: { start: 0 } }); const button = screen.getByRole('button', { name: /count/i });
await userEvent.click(button);
expect(button).toHaveTextContent('count: 1');});วินัยคือ test behaviour ไม่ใช่ implementation assert สิ่งที่ผู้ใช้เห็นและทำ (text ที่มองเห็น, role, interaction) เพื่อให้ refactor ที่รักษา behaviour เดิมไว้ไม่ทำ test พัง
end-to-end ด้วย Playwright
หัวข้อที่มีชื่อว่า “end-to-end ด้วย Playwright”Playwright ขับ browser จริงผ่านหน้าจริง — routing, form submission, navigation — ที่เป็นจุดที่ behaviour ฝั่ง server ของ SvelteKit (load function, form action) ต้อง verify:
import { test, expect } from '@playwright/test';
test('user can sign in', async ({ page }) => { await page.goto('/login'); await page.getByRole('button', { name: 'Sign in' }).click(); await expect(page).toHaveURL('/dashboard');});เก็บ test พวกนี้ให้น้อยและมีคุณค่าสูง — test พวกนี้ช้ากว่า unit และ component test แต่เป็นชั้นเดียวที่พิสูจน์ว่าทุกอย่างทำงานร่วมกันได้