Test

Supertest

kimddakki 2022. 6. 12. 11:05
서버 코드 예제
GET 메서드 API
 - 상태코드 200 리턴
 - JSON 형태로 사용자 이름 전달
 
POST 메서드 API
 - 요청 시 body에 name을 전달 받음
 - 상태코드 201 리턴
 - JSON 형태로 body에 전달 받았던 이름 전달

// app.js
import express from 'express';

const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.get('/user', (req, res) => {
  res.status(200).json({ name: 'modolee' });
});

app.post('/user', (req, res) => {
  const { name } = req.body;

  res.status(201).json({ name })
});

export default app;

Jest 기반으로 테스트 request 생성, expect 모두 supertest 사용
// app.test.js
import request from 'supertest'
import app from './app';

describe('End-to-End Test', () => {
  describe('GET /user', () => {
    test('responds with json', async () => {
      await request(app)
        .get('/user')
        .set('Accept', 'application/json')
        .expect(200)
        .expect('Content-Type', /json/)
        .expect({ name: 'modolee' });
    });
  });

  describe('POST /user', () => {
    test('responds with name in json', async () => {
      await request(app)
        .post('/user')
        .set('Accept', 'application/json')
        .type('application/json')
        .send({ name: 'modolee' })
        .expect(201)
        .expect('Content-Type', /json/)
        .expect({ name: 'modolee' });
    });
  });
});
Jest 기반으로 테스트, request 생성은 supertest를 사용하고, expect는 jest를 사용
// app.test.js
import request from 'supertest'
import app from './app';

describe('End-to-End Test', () => {
  describe('GET /user', () => {
    test('responds with json', async () => {
      const res = await request(app)
        .get('/user')
        .set('Accept', 'application/json');

      expect(res.status).toBe(200);
      expect(res.headers['content-type']).toMatch('/json');
      expect(res.body).toEqual({ name: 'modolee' });
    });
  });

  describe('POST /user', () => {
    test('responds with name in json', async () => {
      const res = await request(app)
        .post('/user')
        .set('Accept', 'application/json')
        .type('application/json')
        .send({ name: 'modolee' })

      expect(res.status).toBe(201);
      expect(res.headers['content-type']).toMatch('/json');
      expect(res.body).toEqual({ name: 'modolee' });
    });
  });
});

 

 

 

Supertest 사용법 (2) - 사용 예제

HTTP assertion을 쉽게 만들어주는 라이브러리 Supertest의 사용법에 대해서 알아봅니다. 사용 예제

velog.io