Home > Web Front-end > JS Tutorial > My Node.js learning path (4)--Unit testing_node.js

My Node.js learning path (4)--Unit testing_node.js

WBOY
Release: 2016-05-16 16:42:34
Original
1219 people have browsed it

Install via NPM:

npm install nodeunit -g

Support command line, browser operation. Various assertions. Modularization under node.js is for method export exports. If it is an object export module.exports, the module is the basis for unit testing. Look at the following node.js code:

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;
Copy after login

./global.js is a local global variable file. Now we use NodeUnit to test the node.js code for the above code:

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();
}
};
Copy after login

test.ok is also what we usually call assertions. For NodeUnit’s unit test program, you can also use node-inspector to debug

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template