• Mocha实践


    公司最近牵起一片Unit Test热,为了迎合公司的口味,我也只能把unit test(其实我写的不是UT,算是integration/aaceptance test了)加入其中。目前来说,nodeJs的ut框架,最有名的应该是TJ大神的mocha了 (有很详细的官方文档:http://visionmedia.github.io/mocha/)。废话少说,切入正题:


    一、安装:mocha是要求全局安装的,那么: npm install -g mocha

    二、组织目录结构:


    我创建了一个子目录test,用来存放所有的test case,mocha默认会测试./test/*.js。同时我也创建了2个bat文件,用来方便执行test case:

    run.bat:执行所有的测试用例,很简单就是调用mocha,-t 5000表示,每个用例5秒超时(默认是2秒)

    @ECHO OFF
    mocha -t 5000 %1 %2 %3 %4 %5 %6 %7 %8 %9

    执行完之后,会看到如下的结果:


    spec.bat:测试,并且显示出每个测试用例的说明(可以用来生成描述文档,spec这些的),代码更简单,就是调用run.bat,且多加了一个参数,-R spec。(mocha还支持很多其他的报告格式的!)

    @ECHO OFF
    run -R spec
    运行之后,可以看到如下结果:



    三、测试用例编写很简单,我用的是BDD,assert用的是should库,也是TJ大神的作品,另外用了request库来执行web service:

    var assert = require("should")
      , request = require('request')
      , settings = require('../settings');
    
    describe('Web Service', function () {
        describe('/', function () {
            it('should return html content', function (done) {
                request(settings.webservice_server, function (error, response, body) {
                    if (error) throw error;
                    response.should.status(200).html;
    
                    done();
                });
            });
        });
    
        describe('/products', function () {
            it('should return an array of products', function (done) {
                request(settings.webservice_server + '/products', function (error, response, body) {
                    if (error) throw error;
                    response.should.status(200).json;
                    response.body.should.not.empty;
                    var products = JSON.parse(response.body);
                    products.should.be.an.instanceOf(Array);
                    done();
                });
            });
        });
    });

    对于异步函数,执行完了,就调用下done。





  • 相关阅读:
    疯子在思考之-异常与return 的差别
    MANIFEST.MF 文件内容完全详解
    疯子奉献-一个符号惹的祸
    疯子在思考之-从日志想到的软件架构
    疯子在思考之java 线程的那点事儿
    linux 自动重启tomcat 脚本
    tomcat 优化及错误All threads (10) are currently busy, waiting. Increase maxThreads错误
    log4j继承
    substring 陷阱
    每天一个随笔
  • 原文地址:https://www.cnblogs.com/puncha/p/3876900.html
Copyright © 2020-2023  润新知