Simple testing REST API with Request

ลองเขียน test สำหรับ รับข้อมูลจาก Web service ดังนี้

test("Get items", function(){
    request('http://localhost:3001/items', function (error, response, body) {
        console.log('error:', error);
        console.log('statusCode:', response && response.statusCode);
        console.log('body:', body);

        expect(response.statusCode).toEqual(200)
    })
})

ตัวอย่างนี้เป็นการทดสอบอย่างง่ายๆว่า Service ที่เรียกไปนั้นทำงานได้ถูกต้อง จะต้องตอบ 200 ออกมา

ต่อมาลองทดสอบในส่วนของข้อมูลที่ได้กลับมาจากการเรียก service ว่าได้ข้อมูลตรงตามที่ต้องการหรือไม่

เพื่อที่จะสามารถนำข้อมูลมาตรวจสอบได้ ต้องทำการแปลงข้อมูลให้อยู่ในรูปแบบ JSON ก่อน เพื่อให้สามารถนำมาใช้งานในภาษา Javascriptได้ ซึ่งในตัวภาษา Javascript สามารถทำได้โดยการใช้ฟังก์ชั่น JSON.parse() เข้ามาช่วยในการแปลงข้อมูล ทำให้ข้อมูลที่ได้ กลายเป็น Javascript object

items = JSON.parse(body)

เมื่อทำการแปลงเป็น Object แล้ว สามารถนำมาตรวจสอบข้อมูลในรูปแบบต่างๆได้ ดังนี้

  • ตวจสอบจำนวนข้อมูล
    expect(items.length).toBe(2)
    
  • ตรวจสอบว่าข้อมูลลำดับแรกมี id เป็น 1 หรือไม่ และ name เป็น Banana หรือไม่

    expect(items[0].id).toBe("1")
    expect(items[0].name).toBe("Banana")
    

    เมื่อนำมารวมกัน จะได้ test case ลักษณะนี้

    test("Get items", function(){
      request('http://localhost:3001/items', function (error, response, body) {
          console.log('error:', error);
          console.log('statusCode:', response && response.statusCode);
          console.log('body:', body);
    
          expect(response.statusCode).toEqual(200)
    
          expect(items.length).toBe(2)
          expect(items[0].id).toBe("1")
          expect(items[0].name).toBe("Banana")
      })
    })
    

results matching ""

    No results matching ""