Supertest

Node.js library ที่ Provide High-level Fluent API ให้เราสามารถทำ API Testing ได้อย่างง่ายๆ มี syntax ในการเขียนเทสที่ทำให้เราอ่านเข้าใจได้ง่าย และยังสามารถทำงานร่วมกันได้ดีกับ Node.js Server Side App.

Jest + Supertest ทำงานร่วมแล้วจะเป็นไง?

เราสามารถนำโค้ดของ API Test ที่เขียนด้วย “Supertest” มารันอยู่บน Jest Test Runner ได้อย่างง่ายๆ เลย ซึ่งจะทำให้เทสของคุณได้ Benefits หลายๆ อย่างเช่น

  • Automatic Parallel API Test by Jest: รันเทสแบบ parallel by default ซึ่งช่วยประหยัดเวลากันรันเทสได้มาก

  • Integrated with popular Javascript Compiler อย่าง Babel, Webpack ได้ เพื่อที่จะสามารถใช้ syntax ใหม่ๆ ของ ES เวอร์ชันใหม่ๆ ได้

  • Many Test Reports and plugins available มี Test Report ให้เราเลือกใช้ได้อย่างหลาย เช่น Junit, HTML Report

install

 npm i --dev-save supertest @types/supertest
#client.ts
import supertest from 'supertest';
import { addMsg } from 'jest-html-reporters/helper';
import { toCurl } from 'request-to-curl';

const request = supertest.agent('https://reqres.in/api');
request.on('response', async (response) => {
    const { request, body, statusCode, headers } = response;
    const data = {
      request: {
        header: request._header,
        url: request.url,
        body: request._data,
        method: request.method,
        curl: request.req.toCurl()
      },
      response: {
        header: headers,
        status: statusCode,
        body,
      }
    }
    await addMsg(JSON.stringify(data, null, 2));
});

export default request;

โดย Spertest อนุญาตให้เรา listen to event ต่างๆ ได้ (เช่น error, response event) ดังนั้นผมจึงทำการ listen response event ไว้เพื่อที่จะเอาไว้ log http request/response ลงไปใน Test Report อีกที (เผื่อเอาไว้ใช้ debug ในกรณีที่ที่เกิด test failed) นอกจากนี้ผมยังใช้ Library เสริมอย่าง request-to-curl เพื่อใช้ทำการแปลง http request เป็น curl command เผื่อว่าจะเอาไปใช้ call ผ่าน curl ทีหลังได้อีกที

import request from './client';

describe('Users', () => {
  describe('List Users', () => {
    it('list all users', () => {
      return request.get('/users').expect(200);
    });
    it('gets user by id', async () => {
      return request.get('/users/2')
        .expect(200)
        .then(response => {
          expect(response.body.data.first_name).toEqual('Janet')
        });
    });
  });

  describe('Create User', () => {
    it('create new user failure', () => {
      return request.post('/users')
        .send({
          name: 'nottyo',
          job: 'developer'
        })
        .expect(201);
    });
  })
});

จะเห็นได้ว่าการเขียน API Test ด้วย “Supertest” นั้นจะเป็นลักษณะ Chaining Calls ไปเรื่อยๆ เช่น request.get(‘/users’).expect(200) แบบนี้ได้เลย ดูใช้งานง่ายมากๆ เลยว่ามั้ยครับ ซึ่ง Supertest รองรับการทำ API Test ทุกรูปแบบ HTTP

Last updated