TESTING CORE · 122
Browser E2E:從使用者角度保護完整 Journey
E2E test 讓真實 Browser 走過導航、表單、network、UI 更新。它最適合保護少數關鍵 user journeys,不適合把每個純函式都拿 Browser 測。
Learning outcomes
- 能選 user-facing locator。
- 能避免固定 sleep。
- 能建立 deterministic test setup。
- 能決定哪些 flow 值得 E2E。
1. User journey
test(
"student creates course",
async ({ page }) => {
await page.goto("/");
await page
.getByLabel("Title")
.fill("JavaScript");
await page
.getByRole(
"button",
{ name: "Save" }
)
.click();
await expect(
page.getByText(
"JavaScript"
)
).toBeVisible();
}
);2. Locator 應代表 UI contract
Role、label、accessible name 通常比 nth-child / implementation class 更接近使用者真正互動方式,也更能推動 accessibility。
3. Auto-waiting,不要到處 sleep
// brittle
await sleep(5000);
// better concept
await expect(
result
).toBeVisible();等待「需要成立的狀態」,不是等待固定秒數。
4. Test isolation
E2E 也需要 controlled user/data。若每次都沿用同一 production account,test 容易互相污染、受真實資料影響。
5. Trace / screenshot / network evidence
E2E fail 時,保留 screenshot、trace、console/network log 能把「按鈕沒反應」拆成 UI locator、request、server 或 data failure。
Project checkpoint:Course Workspace critical flow
Login
↓
Create course
↓
Course appears
↓
Reload
↓
Course still exists
↓
Sign out這條 flow 一次跨 Browser、Auth、API、DB,非常適合作少量關鍵 E2E。
Test pyramid / portfolio
大量 fast unit + 足夠 integration + 少量高價值 E2E。不是越接近 production 的 test 越多越好。
Knowledge check
- 為什麼 label/role locator 通常較穩?
- 固定 sleep 的問題?
- 哪些功能值得 E2E?
- 替 Course Workspace 設計一條 5-step critical journey。