zoukankan      html  css  js  c++  java
  • 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。





  • 相关阅读:
    不可或缺 Windows Native (15)
    不可或缺 Windows Native (14)
    不可或缺 Windows Native (13)
    不可或缺 Windows Native (12)
    不可或缺 Windows Native (11)
    不可或缺 Windows Native (10)
    不可或缺 Windows Native (9)
    不可或缺 Windows Native (8)
    不可或缺 Windows Native (7)
    不可或缺 Windows Native (6)
  • 原文地址:https://www.cnblogs.com/puncha/p/3876900.html
Copyright © 2011-2022 走看看