잊지 않겠습니다.

mocha를 이용한 express application test 방법

yo-express를 이용한 application을 test 하는 방법을 한번 알아보고자합니다.

npm module 설치

web에 대한 test는 supertest를 사용하는 것이 좋습니다. 직관적인 사용에도 좋고, mocha에서 사용하기에도 매우 편합니다.

npm install supertest --save-dev

root에 test folder 생성

app.test.js 파일 생성

express application을 먼저 구동하는 것이 필요합니다. 이는 원 app.js에서 구성되는 express start와 sequelize model의 초기화 과정에 대한 process를 실행해야지 되는것을 의미합니다. test라는 상대경로로 옮겨왔기 때문에 경로의 depth가 달라지는 것에 주의할 필요가 있습니다. 그리고 test의 시작전에 항시 실행되어야지 되는 global before이기 때문에 before로 구성되어야지 됩니다.

'use strict';

before(function () {
  var express = require('express'),
    config = require('../config/config'),
    db = require('../app/models');
  var agent = require('supertest');

  var app = express();

  require('../config/express')(app, config);

  db.sequelize
    .sync()
    .then(function () {
      app.listen(config.port, function () {
        console.log('Express server listening on port ' + config.port);
      });
    }).catch(function (e) {
      throw new Error(e);
    });
  console.log('before');
  global.app = app;
  global.agent = agent(app);
});

mocha로 test running

이제 mocha를 이용해서 다음 command로 실행이 가능합니다.

mocha test/app.test.js test/**/*.test.js

mocha.opts 설정

좀더 편한 test 환경을 만들기 위해서 mocha.optsapp.test.js를 넣어두면 편합니다.

--timeout 5000
--full-trace
test/app.test.js

이 때, mocha.opts파일의 위치는 다음과 같이 구성합니다.

└── test
    ├── app.test.js
    ├── controllers
    ├── mocha.opts
    └── models

controller test code 작성

controller test code는 다음과 같이 구성될 수 있습니다. app.test.js에서 supertest의 request를 global.agent로 지정했기 때문에, test에서는 언제나 agent를 접근 가능해서 test code를 작성하기 좀 더 편해집니다.

'use strict';

var assert = require('assert');

describe('func01', function () {
  it('test', function () {
    console.log('abc');
  });

  it('call /', function (done) {
    agent
      .get('/')
      .expect(200)
      .end(function (err, res) {
        // console.log(res);
        done(err);
      });
  });

  it('call / - 2', function (done) {
    agent
      .get('/')
      .expect(500)
      .end(function (err, res) {
        done();
      });
  });
});

Summary

nodejs는 compile 언어가 아니기 때문에, 실행되기 전까지 정상적인 code를 작성했는지를 헛갈릴 수 있습니다. 개인적으로는 원론적으로 test를 거치지 않으면 compile 언어 역시 마찬가지로 문제가 있다고 생각합니다만. test를 잘 만들어주는 것과 test를 잘 할 수 있도록 해주는 것은 자신 뿐 아니라 다른 개발자들에게도 매우 좋은 일들입니다. 이건 정말 잘 할 필요가 있다고 생각합니다.

mocha를 이용한 test는 매우 유용합니다. 만약에 nodejs를 이용한 개발을 하고 있다면, test를 어떻게 할지에 대한 고민을 꼭 해보시길 바랍니다.

Posted by Y2K
,