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

การทดสอบ API

การทดสอบคือสิ่งที่ให้คุณเปลี่ยนแปลง API ได้อย่างมั่นใจ สามชั้น แต่ละชั้นดักจับบั๊กคนละประเภท ให้ความครอบคลุมที่ดีโดยไม่ต้องลงแรงซ้ำซ้อน

flowchart TD
  U[Unit: handlers, validation, pure logic - many, fast] --> I[Integration: real routes end-to-end - fewer]
  I --> C[Contract: responses match the OpenAPI spec - focused]
unit test จำนวนมากที่รวดเร็ว, integration test น้อยกว่า, contract check ที่เจาะจง
  • Unit tests — ทดสอบชิ้นส่วนล้วน ๆ เช่น validator, ตัวช่วย pagination, ตัว map error เร็วและมีจำนวนมาก
  • Integration tests — ส่ง request จริงผ่าน router ตัวจริงแล้วตรวจสอบ status, header และ body สิ่งเหล่านี้ดักจับบั๊กการเชื่อมต่อที่ unit test มองข้าม
  • Contract tests — ตรวจสอบว่า response สอดคล้องกับ schema ของ OpenAPI เพื่อให้การสร้างจริงและ contract ที่เผยแพร่ไปไม่มีวันคลาดเคลื่อนกัน

เฟรมเวิร์กอย่าง Hono เปิดให้ใช้ app.request(...) คุณจึงเรียก route แบบ in-process ได้โดยไม่ต้องผ่าน network

JavaScript

แต่ละ endpoint ให้ทดสอบทั้ง happy path และ failure path ได้แก่ status code ที่ถูกต้อง รูปร่างของ response error body ของ input ที่ไม่ถูกต้อง (ตรงกับ problem+json ของคุณหรือเปล่า) การบังคับ auth ในจุดที่ควรมี และ metadata ของ pagination บน collection

Test Typeทดสอบอะไรเหมาะกับ
Unit testlogic ใน function แยกvalidation, business rule
Integration testendpoint จริง + database จริงhappy path, error path
Contract testrequest/response match OpenAPI specAPI evolution
E2E testuser journey ทั้งหมดcritical flow เช่น checkout

Test เฉพาะ Happy Path อาการ:

  • test ที่ pass request ถูกต้อง — resource สร้าง, status 201
  • ไม่ test: validation error, auth failure, not found, conflict
  • test error path ทุก status code ที่ API document ไว้

Mock Database ใน Integration Test อาการ:

  • integration test mock database — query จริงไม่ได้รัน
  • SQL ผิด, constraint ผิด — pass ใน test แต่ fail ใน production
  • ใช้ test database จริง (SQLite in-memory หรือ test container)

💡 ตัวอย่างจากของจริง

Stripe:

  • test mode API key — รัน test บน Stripe environment จริงโดยไม่ charge จริง
  • webhook testing ผ่าน Stripe CLI: stripe listen --forward-to localhost:3000/webhook

GitHub:

  • API test ผ่าน sandbox environment
  • contract test ด้วย OpenAPI spec — CI fail ถ้า response ไม่ match spec
การทดสอบชั้นใดที่ส่ง request จริงผ่าน router ตัวจริง?
contract test ป้องกันสิ่งใดโดยเฉพาะ?
ทำไมจึงต้องทดสอบ failure path อย่างชัดเจน?