Node.jsでユニットテスト

Node.jsでユニットテストしてみます。
まずはNode.jsのインストールから。


■Node.jsのインストール(NVM使用)

$wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.18.0/install.sh | bash

環境変数を詠み込むため、Terminalを閉じてもう一度開く

$nvm ls-remote
$nvm install vX.X.X ※使用するバージョンを指定
$node -v


ユニットテストライブラリのインストール

$sudo apt-get install npm
$sudo npm install mocha
$sudo npm install power-assert
$sudo npm install nock
$sudo ln -s "$(which nodejs)" /usr/local/bin/node


■helloWorld.js

exports.greet = function() { 
	return "Hello World!!"; 
}


■helloWorldTest.js

var assert = require('assert');
var module = require('./helloWorld');
 
describe('greet', function () {
	it('戻り値が正しいこと', function () {
		assert.equal(module.greet(), 'Hello World!!');
	});
});


■http.js

var https = require('https');
var url = "https://www.google.co.jp";

exports.getData = function (done) {
	
	https.get(url, function (res) {
		
		var response = '';
		
		res.on('data', function (chunk) {
			response += chunk;
		});
		
		res.on('end', function () {
			console.log(response);
			done(null, response);
		});
	
	}).on('error', function (e) {
		console.log(e.message);
		done(e);
	});
}


■httpTest.js

var nock = require('nock');
var assert = require('power-assert');
var module = require('./http.js');

var url = 'https://www.google.co.jp';
var path = '/';

describe('HTTPレスポンスのMockテスト', function () {
	
	it('getDataのテスト', function (done) {
		
		// HTTPレスポンスのMock作成
		nock(url).get(path).reply(200, 'GoogleのHTML'); ※Mockで指定した値が返却される(Webサイトにアクセスしない)
		
		// テスト実行
		module.getData(function (err, response) {
			assert(response == 'GoogleのHTML');
			done();
		})
	});
});


ユニットテスト実行

$mocha helloWorldTest.js
$mocha httpTest.js