首页 > web前端 > js教程 > 正文

我的Node.js学习之路(四)--单元测试_node.js

WBOY
发布: 2016-05-16 16:42:34
原创
1175 人浏览过

通过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 &#63; (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来调试

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!