Hatena::ブログ(Diary)

電脳戦士ハラキリ -SE道とは死ぬ事と見つけたり- このページをアンテナに追加 RSSフィード

JavaScriptやKinect, OpenNI, iOSについて。Twitterは@hagino3000
SIerで兵隊(スーツ着て客先常駐)をやっていた時期が私にもありました……。

2011-04-11

nodeunitを使ったテストコード

サーバーにnodeを使いつつTDDをするためにnodeunitを使ってみた。試しにmongoDBの操作を直列で記述できるラッパーを作って、それのテストケースを3つ書いた。

テストコード

var mongodb = require('mongodb');
var Transaction = require('./mongotransaction').MongoTransaction;

var db, case1 = {};

case1.setUp = function(next) {
  var server = new mongodb.Server("127.0.0.1", 27017, {});
  db = new mongodb.Db('test', server, {});
  next();
}

case1["Open and close DB"] = function(test) {
  new Transaction(db)
    .exec(function(next) {
      test.equal(this.db.state, "notConnected");
      next();
    })
    .openDB()
    .exec(function(next, client) {
      test.equal(this.db.state, "connected");
      next(client);
    })
    .closeDB()
    .exec(function(next, client) {
      test.equal(this.db.state, "notConnected");
      test.done();
    })
    .start();
};

case1["Insert document"] = function(test) {
  var colName = 'unitTest';

  new Transaction(db)
    .openDB()
    .removeAll(colName)
    .insert(colName, {name: 'Insert test'})
    .find(colName, {}, {})
    .openCursor('toArray')
    .exec(function(next, cx) {
      test.equal(cx.arr.length, 1);
      test.equal(cx.arr[0].name, 'Insert test');
      test.done();
      next(cx.db);
    })
    .closeDB()
    .start();
}

case1["Handle Exception and close DB"] = function(test) {
  var colName = 'unitTest';

  new Transaction(db)
    .openDB()
    .removeAll(colName)
    .find(colName, {}, {})
    .openCursor('toArray')
    .exec(function(next, cx) {
      // Throws exception (cx.arr[10] is undefined)
      cx.arr[10].toString();
      test.ok(false, "This line shoud not be called");
    })
    .onFailure(function(e) {
      test.equal(this.db.state, 'notConnected');
      test.ok(true, "handle failure succeeded");
      test.done();
    })
    .start();
}

module.exports = require('nodeunit').testCase(case1);

実行結果

f:id:hagino_3000:20110411194636p:image


いいですね。QUnitよりも非同期処理のテストがスマートに書ける。

簡単な使い方は次のエントリがわかりやすい

高度な使い方はGithubリポジトリのreadmeに詳しく書いてある

はてなユーザーのみコメントできます。はてなへログインもしくは新規登録をおこなってください。

トラックバック - http://d.hatena.ne.jp/hagino_3000/20110411/nodeunit