Supertest · คำขอ HTTP แรก
Status Assertion และ Assertion Style
เปรียบเทียบ `.expect()` ของ Supertest กับ Jest `expect()` และเลือกใช้ให้ชัด
สองวิธีตรวจ status ที่ถูกต้อง
Supertest ให้ `.expect(status)` สำหรับ assertion ที่อยู่ใน request chain ส่วน Jest ให้ `expect(response.status)` หลังจากเรา await response ทั้งสองแบบตรวจสิ่งเดียวกัน แต่เหมาะกับรูปแบบ test ต่างกัน
เลือก style ตาม teaching intent
| สถานการณ์ | style ที่แนะนำ | เหตุผล |
|---|---|---|
| ตรวจ status อย่างเดียว | .expect(200) | request chain สั้นและอ่านเป็น contract |
| ตรวจ body หลาย field | await + Jest expect | เก็บ response ไว้ใช้หลาย assertion |
| ตรวจ error และ log context | await + Jest expect | อ่าน status, body และ message พร้อมกัน |
กฎสำคัญ
clarity
อย่า assert ซ้ำโดยไม่มีเหตุผล
เลือกตรวจ status ผ่าน `.expect()` หรือ Jest อย่างใดอย่างหนึ่งใน test เดียว เว้นแต่กำลังสอนความแตกต่าง
body
status ไม่พอสำหรับ public contract เสมอไป
create ที่คืน 201 แต่ body ขาด id ก็ยังเป็น regression ได้