[Mocha] SuperTest (1)

권민제·2021년 8월 7일
1

TDD

목록 보기
3/3
post-thumbnail

supertest

HTTP 테스트를 쉽게 만들어주는 라이브러리
superagent를 기반으로한 HTTP 검증 라이브러리

⬇️ Install

supertest

$ npm install --save-dev supertest

chai

assertion 모듈
Should, Expect, Assert 인터페이스 제공

$ npm install --save-dev chai

➡️ Ex (es6문법으로 작성됨)

폴더구조

test_node
├── node_modules
├── test
│   ├── test.spec.js
├── .babelrc 
├── app.js
└── package.json

package

{
  "name": "test_node",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "test": "mocha ./test/test.spec.js -r @babel/register"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
  },
  "devDependencies": {
    "@babel/cli": "^7.14.8",
    "@babel/core": "^7.14.8",
    "@babel/node": "^7.14.7",
    "@babel/polyfill": "^7.12.1",
    "@babel/preset-env": "^7.14.8",
    "@babel/register": "^7.14.5",
    "babel-loader": "^8.2.2",
    "chai": "^4.3.4",
    "mocha": "^9.0.2",
    "supertest": "^6.1.3"
  }
}

app

import express from 'express';

const app = express(); 

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

app.get('/test', (req, res) => { // GET 응답 테스트
    res.status(200).send({
        success : true,
        query : req.query,
        message : 'test'
    });
});

app.post('/test', (req, res) => { // POST body request 테스트
    res.status(200).send({
        success : true,
        data : req.body,
        message : 'test'
    });
});

export default app;

간단하게 respons , request body, cookie, file upload를 테스트를 할 수 있는 express app을 만들었다

test.spec

import app from "../app";
import request from "supertest";
import { expect } from "chai";

const users = [
    {id: 1, email: 'john@gmail.com', name: 'John'},
    {id: 2, email: 'bob@gmail.com', name: 'Bob'},
    {id: 3, email: 'anna@gmail.com', name: 'Anna'}
]

describe('GET /test',() =>{
    users.forEach(({id}, index) => {
        const req = request.agent(app); 
      	// 각 유저마다 매번 새로운 요청 생성, agent로 생성하여 요청 지속 가능 ( Cookie & Session )
        it('['+index+'] response check / user_id : '+id, done => {
            req
            .get('/test') // request RestAPI 설정
            .query({user_id : id}) // request query로 보낼 데이터 설정
            .expect(200) // response stateCode 200 expect
            .then( res => { // response
                console.log(res.body);
             	// exprect().to.equal() / js === 비교와 같은 깊은 비교
                expect(res.body.query.user_id).to.equal(String(id)) // query에 저장된 user_id 비교 expect
                expect(res.body.success).to.equal(true); // success value expect
                done();
            })
            .catch( err => { // err handling
                console.log('GET /test ERROR : ', err);
                done(err);
            })
        })
    })  
});


describe('POST /test',() =>{
    users.forEach(({id, email ,name}, index) => {
        const req = request.agent(app); 
      	// 각 유저마다 매번 새로운 요청 생성, agent로 생성하여 요청 지속 가능 ( Cookie & Session )
        it('['+index+'] response check/ user_id : '+id, done => {
            req
            .post('/test')// request RestAPI 설정
            .set('Content-Type', 'application/json') // request Content-Type 설정
            // .type('application/json') // request Content-Type 설정 .type()으로 대체가능
            .set('Accept', 'application/json') // request Accept 설정
            .send({user_email : email, user_name : name}) // request body로 보낼 데이터 설정
            .expect(200) // response stateCode 200 expect
            .expect('Content-Type', /json/) // request Content-Type expect json형태로 응답지정
            .then( res => { // response
                console.log(res.body);
                expect(res.body.data.user_email).to.equal(email); // body에 저장된 user_email 비교 expect
                expect(res.body.data.user_name).to.equal(name); // body에 저장된 user_name 비교 expect
                expect(res.body.success).to.equal(true); // success value expect
                done();
            })
            .catch( err => { // err handling
                console.log('POST /test ERROR : ', err);
                done(err);
            })
        })
    });
});

✅ 실행

$ npm test

🖥️ 결과

🔗 Github

https://github.com/gwon713/nodejs-mocha

profile
성장하는 개발자!

0개의 댓글