posts - 930,  comments - 588,  views - 402万
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

在专业化的软件开发过程中,无论什么平台语言,现在都需要UnitTest单元测试. Node.js有built-in的Assert。 今天让我们来看一下Node.js的单元测试。在这儿我们使用nodeunit,

nodejs
通过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 ? (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来调试。

希望对您软件开发有帮助。您可能感兴趣的文章:

Node.js调试

 


作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog

posted on   PetterLiu  阅读(9586)  评论(2编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
历史上的今天:
2011-06-06 使用Unity2.0的Interceptor实现简单AOP
点击右上角即可分享
微信分享提示