通過NPM安裝:
npm install nodeunit -g
支持命令行,浏覽器運行. 各種斷言。 在node.js下模塊化對於方法導出exports, 如果是對象導出module.exports,模塊兒是單元測試的基礎,看下面的node.js代碼:
var fs = require('fs'), global=require('./global.js'); var utils = { startWith: function(s1, s) { if (s == null || s == "" || this.length == 0 || s.length > this.length) return false; if (s1.substr(0, s.length) == s) return true; else return false; return true; }, /* Generate GUID */ getGuid: function() { var guid = ""; for (var i = 1; i <= 32; i++) { var n = Math.floor(Math.random() * 16.0).toString(16); guid += n; } return guid; }, /* add log information */ writeLog: function(log) { if(!log) return; var text = fs.readFileSync(global.logFile, "utf-8"), _newLog = text ? (text + "\r\n" + log) : log; fs.writeFile(global.logFile, _newLog, function(err){ if(err) throw err; }); } }; exports.utils=utils;
./global.js是一個本地全局變量文件,現在我們對以上代碼使用NodeUnit做測試的node.js代碼:
var utils=new require('./utils.js'); this.TestForUtils = { 'TestgetGuid': function (test) { var guid=utils.utils.getGuid(); test.ok(!!guid, 'getGuid should not be null.'); test.done(); }, 'TestWritelog': function (test) { var flag=false; utils.utils.writeLog("test message"); flag=true; test.ok(flag,'writeLog'); test.done(); }, 'TestStartWithWords': function (test) { var name="ad_123"; test.ok(utils.utils.startWith(name, "ad_"),"startwith method should be ok"); test.done(); } };
test.ok也是通常我們說的斷言。對於NodeUnit的單元測試程序,也可以使用node-inspector來調試