DIV CSS 佈局教程網

我的 Node.js 學習之路(四):使用 NodeUnit 做單元測試
編輯:關於JavaScript     

Node.js 的模組化特性是單元測試的基礎——用 exports 導出方法、用 module.exports 導出物件,都能讓測試變得直觀。本文用 NodeUnit 來示範如何為自訂模組撰寫測試。

先透過 NPM 安裝:

npm install nodeunit -g

它支援命令列與瀏覽器運行,提供各種斷言。以下是一個待測的工具模組 utils.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 測試:

 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 就是我們常說的斷言,而 test.done() 則告訴測試框架當前用例已結束。對於 NodeUnit 的單元測試程式,也可以搭配 node-inspector 來進行除錯,讓測試與排查都更順手。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved