Supertest · สร้าง E2E Test Harness
จัดการ App Lifecycle
ใช้ beforeAll และ afterAll เปิด/ปิด application อย่างปลอดภัย
เปิดครั้งเดียว ปิดให้ครบ
E2E app และ database client เป็น resource ที่ต้องเปิดและปิดอย่างตั้งใจ `beforeAll` เหมาะกับการสร้าง app ครั้งเดียว ส่วน `afterAll` ต้อง await `app.close()` เพื่อให้ test process จบโดยไม่เหลือ open handle
lifecycle ขั้นต่ำTS
ถ้าเปิด Prisma client แยกจาก app ต้องปิด resource นั้นใน lifecycle ที่เหมาะสมด้วย
แยก beforeAll กับ beforeEach
| hook | ทำอะไร | ตัวอย่าง |
|---|---|---|
| beforeAll | เตรียม resource ที่แชร์ได้ | create app, compile module |
| beforeEach | reset state ของ test ปัจจุบัน | ล้าง fixture หรือ database rows |
| afterAll | คืน resource ภายนอก | app.close(), prisma.$disconnect() |
กฎสำคัญ
isolation
อย่าใช้ afterAll แทน cleanup ระหว่าง test
การปิด app ตอนจบไม่ได้ป้องกันข้อมูลจาก test ก่อนหน้ารั่วเข้า test ถัดไป
async
อย่าทิ้ง promise
ใส่ `await` ให้ operation ที่เปิด/ปิด resource และ request เพื่อให้ runner รอผลจริง