ข้ามไปยังเนื้อหา

Testing

การ test แอป Svelte คือ pyramid เดียวกับ frontend ทั่วไป โดยมี helper ที่รู้จัก Svelte ตรงชั้น component:

ชั้นเครื่องมือครอบคลุมอะไร
UnitVitestlogic ล้วน, utility และ runed .svelte.js module
Component@testing-library/svelte + Vitestcomponent ที่ render ใน jsdom — behaviour ไม่ใช่ internals
End-to-endPlaywrightแอปจริงใน browser จริง ข้ามหลายหน้า
flowchart TB
  e2e["Playwright: end-to-end (few)"] --> comp["Testing Library: components (some)"]
  comp --> unit["Vitest: logic + runed modules (many)"]
testing pyramid สำหรับแอป Svelte

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() เมื่อจำเป็น

@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 พัง

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.getByLabel('Email').fill('[email protected]');
await page.getByRole('button', { name: 'Sign in' }).click();
await expect(page).toHaveURL('/dashboard');
});

เก็บ test พวกนี้ให้น้อยและมีคุณค่าสูง — test พวกนี้ช้ากว่า unit และ component test แต่เป็นชั้นเดียวที่พิสูจน์ว่าทุกอย่างทำงานร่วมกันได้

หลักการนำทางเวลา test component ด้วย Testing Library คืออะไร?
จะ test reactive state ใน `.svelte.js` module อย่างไร?
เครื่องมือไหน verify flow sign-in เต็มรูปแบบข้ามหน้าจริงใน browser?