Vitest · Async Tests
`.resolves`
ตรวจค่าที่ Promise resolve กลับมาโดยใช้ matcher ต่อเนื่อง
resolves เปิด Promise ให้ matcher
เมื่ออยากตรวจค่าที่ Promise resolve กลับมา สามารถใช้ expect(promise).resolves แล้วต่อ matcher ได้ รูปแบบนี้ลดตัวแปรกลาง แต่ assertion ทั้งชุดจะกลายเป็น asynchronous จึงต้อง await assertion ด้วย
กฎสำคัญ
ต้อง await resolves assertion
ถ้าไม่ await test อาจจบก่อน matcher ทำงานและเกิด false positive ได้
ใช้กับ success path
resolves เหมาะเมื่อ contract ระบุว่า Promise ควรสำเร็จและคืนค่าชนิดใด
อ่าน resolves เป็นประโยคเดียว
expect(promise).resolves.toEqual(expected) อ่านได้ว่า “ตรวจว่า Promise จะ resolve เป็น expected” คำว่า resolves ทำหน้าที่เปิด Promise ให้ matcher ด้านขวา แต่ไม่ได้ทำให้ test รอแทนเรา จึงยังต้องมี await ด้านหน้า
เลือก await หรือ resolves
| รูปแบบ | เหมาะเมื่อ |
|---|---|
| const value = await fn(); expect(value).toEqual(...) | ต้องใช้ value ต่อหลายบรรทัดหรืออยากแยก AAA |
| await expect(fn()).resolves.toEqual(...) | มี assertion ตรง ๆ หนึ่งชุดและต้องการลด boilerplate |
| expect(fn()).toEqual(...) | ไม่เหมาะกับ Promise เพราะยังไม่ได้รอผล |
สองรูปแบบไม่ได้เปลี่ยน behavior
เลือกจากความอ่านง่ายของ test ไม่ใช่จากความสั้นอย่างเดียว ถ้า await แบบแยกตัวแปรทำให้เห็น flow ชัดกว่า ให้ใช้รูปแบบนั้น
แบบฝึก: เขียน resolves assertion
ใช้ resolves ตรวจว่า loadStatus คืนคำว่า ready
งานที่ต้องทำ
- ประกาศ test callback เป็น async
- ใช้ await หน้า expect(...).resolves
- ต่อ matcher ที่ตรวจ string exact
ลองทำด้วยตัวเองก่อน แล้วค่อยเปิดเฉลยเพื่อเทียบแนวคิดและรายละเอียด