My Node. js learning path (4) -- unit test _ node. js

Source: Internet
Author: User
In the professional software development process, no matter what platform language, now UnitTest is required. Node. js has the Assert of built-in. Today, let's take a look at the Node. js unit test. Here we use nodeunit for NPM installation:

Npm install nodeunit-g

Supports command line and browser running. Various assertions. In node. js, modularize the method to export exports. If it is an object to export module. exports, the module is the basis of the unit test. See 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;elsereturn 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 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();}};

Test. OK is also a general asserted. You can also use node-inspector to debug the unit test program of NodeUnit.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.