Node TDD 도구

Node.js

Node TDD

Node.js에서 TDD를 하기위하여 필요한 라이브러리를 소개한다.

  • Mocha
    • Mocha는 테스트 코드를 돌려주는 Test Runner이다.
  • Should
    • assertion(검증) 라이브러리이다.
  • Supertest
    • express 통합 테스트용 라이브러리이다.

Mocha

Mocha 공식 사이트 Link

Mocha는 테스트 코드를 돌려주는 Test Runner이다.
describe()를 사용하여 모카에서는 테스트 환경을 구현한다.
it()을 사용하여 테스트 케이스를 작성한다.

1
$ npm install mocha --save-dev  

mocha는 개발환경에서만 필요한 라이브러리이기 때문에 -dev에 설치한다.

하나의 예시를 들어보자, 예시는 문자열이 들어오면 전체다 대문자로 바꿔주는 함수이다.

먼저 TDD 원칙인 Red-Green-Refactor 원칙을 통하여 Red 상태를 만들어본다.

1
2
3
4
5
//test.js
function convertToUppercase(str) {
return str
}
module.exports = {convertToUppercase}

test하고자하는 파일은 spec을 추가해주면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
//test.spec.js
const assert = require('assert');
const test = require('./test');

describe('convertToUppercase 함수는', () => {
it('String을 Int로 변환한다', (done) => {
const actual = test.convertToUppercase('asd');
const expected = 'ASD';
assert.equal(actual, expected);
done();
});
});

위의 코드를 실행해보면 ‘ASD’를 기대했는데 ‘asd’가 와서 내가 의도한 대로 red가 나왔다.
이제 green으로 만들어보자.

명령어를 실행하는 방법: node_modules/.bin/mocha test.spec.js

1
2
3
4
5
6
//test.js  
function convertToUppercase(str) {
return str.toUpperCase();
}

module.exports = {convertToUppercase}

String의 str.toUpperCase()를 사용하여 Green상태로 만들었다.
Refactor의 경우 아래의 should를 사용하여서 해보겠다.

Should

should 공식 사이트 Link

should는 assertion(검증) 라이브러리이다.
Node.js의 공식문서에는 assert를 사용하지말고 서드파티 라이브러리를 사용하라고 개시되어있다.
가독성 높은 테스트 코드를 만들 수 있다.

  • 하나의 문장처럼 만들기 때문이다.
1
2
3
4
5
6
7
8
9
10
11
12
13
//test.spec.js
const assert = require('assert');
const should = require('should');
const test = require('./test');

describe('convertToUppercase 함수는', () => {
it('String을 Int로 변환한다', (done) => {
const actual = test.convertToUppercase('asd');
const expected = 'ASD';
actual.should.be.equal(expected);
done();
});
});

should를 사용하여서 refactor를 진행하였다.

SuperTest

supertest 주소 Link

supertest는 통합 테스트로써 API의 기능을 테스트할 수 있다.
supertest는 express 통합 테스트용 라이브러리이다.
내부적으로 Express Server를 구동시켜 실제 요청을 보낸뒤 결과를 검증한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//index.js
const express = require('express');
const app = express();

const people = [{
name: 'hook',
age: 28
}, {
name: 'john',
age: 52
}];

app.get('/people', (req, res) => {
res.json(people);
});

app.listen(3000, () => {
console.log('hello~')
});

module.exports = app;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//index.spec.js
const supertest = require('supertest');
const should = require('should');
const app = require('./index');


describe('GET /people은 ', () => {
it('People Array로 응답한다.', (done) => {
supertest(app)
.get('/people')
.end((err, res) => {
const actual = res.body;
const expected = Array;
actual.should.be.instanceOf(expected);
done();
});
});
});

test 명령어 편하게 입력하기.

기존의 node_modules/.bin/mocha test.spec.js 를 통하여 테스트하기는 번거로움이 있었다.
그것을 해결하는 방법이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{

"scripts": {
"test": "mocha",
"start": "node index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.16.4"
},
"devDependencies": {
"mocha": "^5.2.0",
"should": "^13.2.3",
"supertest": "^3.3.0"
},
"description": ""
}

이런식으로 mocha를 명시해두면 자동으로 node_modules/.bin/mocha를 찾는다.
이때 사용법은 mocha test index.spec.js 를 입력하면 된다.

마치며

아직 부족한 부분이 많다보니 잘못된부분을 지적해주시면 감사하겠습니다!!
TDD를 지속적으로 공부하고 발전해서 믿을 수 있는 코드를 작성하는 개발자가 되어야겠다.

Share