我的Node.js学习之路(四)--单元测试
通过NPM安装:
npminstallnodeunit-g
支持命令行,浏览器运行.各种断言。在node.js下模块化对于方法导出exports,如果是对象导出module.exports,模块儿是单元测试的基础,看下面的node.js代码:
varfs=require('fs'), global=require('./global.js'); varutils={ startWith:function(s1,s){ if(s==null||s==""||this.length==0||s.length>this.length) returnfalse; if(s1.substr(0,s.length)==s) returntrue; else returnfalse; returntrue; }, /*GenerateGUID*/ getGuid:function(){ varguid=""; for(vari=1;i<=32;i++){ varn=Math.floor(Math.random()*16.0).toString(16); guid+=n; } returnguid; }, /*addloginformation*/ writeLog:function(log){ if(!log)return; vartext=fs.readFileSync(global.logFile,"utf-8"), _newLog=text?(text+"\r\n"+log):log; fs.writeFile(global.logFile,_newLog,function(err){ if(err)throwerr; }); } }; exports.utils=utils;
./global.js是一个本地全局变量文件,现在我们对以上代码使用NodeUnit做测试的node.js代码:
varutils=newrequire('./utils.js'); this.TestForUtils={ 'TestgetGuid':function(test){ varguid=utils.utils.getGuid(); test.ok(!!guid,'getGuidshouldnotbenull.'); test.done(); }, 'TestWritelog':function(test){ varflag=false; utils.utils.writeLog("testmessage"); flag=true; test.ok(flag,'writeLog'); test.done(); }, 'TestStartWithWords':function(test){ varname="ad_123"; test.ok(utils.utils.startWith(name,"ad_"),"startwithmethodshouldbeok"); test.done(); } };
test.ok也是通常我们说的断言。对于NodeUnit的单元测试程序,也可以使用node-inspector来调试