Supertest · JWT Authentication และ Request State
Unauthenticated Request
พิสูจน์ว่า protected route ปฏิเสธ request ที่ไม่มี token
ไม่มี token ต้องถูกปฏิเสธ
Protected route ต้องไม่เปิดให้ request ที่ไม่มี credential ผ่านเพียงเพราะ route ตอบได้ การทดสอบ unauthenticated request ช่วยยืนยันว่า guard ถูกติดตั้งกับ route จริง
401 ต่างจาก 403
| status | ความหมาย | ตัวอย่าง |
|---|---|---|
| 401 | ยังยืนยันตัวตนไม่ได้ | ไม่มี token หรือ token ใช้ไม่ได้ |
| 403 | ยืนยันตัวตนแล้วแต่ไม่มีสิทธิ์ | role หรือ ownership ไม่ผ่าน |
กฎสำคัญ
meaning
ชื่อ test ต้องบอกสาเหตุ
`returns 401 without a token` ช่วยแยกจาก `returns 403 for a user role` ได้ทันทีเมื่อ fail
assertion
อย่าพึ่งพา error message อย่างเดียว
status เป็น contract หลัก ส่วน message ตรวจเมื่อมีข้อความที่ caller ใช้จริง