代码改变世界

[Node.js] BDD和Mocha框架

2014-11-22 17:42  莫耶  阅读(2281)  评论(0编辑  收藏  举报

原文地址:http://www.moye.me/2014/11/22/bdd_mocha/

引子

今天造了个轮子:写了个深拷贝任意JavaScript对象的模块(事实上npm上已经有类似的模块,纯造轮子 :) 虽然是个轮子,依然是需要测试的,保不齐还有除我之外的人会用到。那么问题来了,应该怎么测试?

从需求视角来看,这样的模块涉及到的数据类型繁多(Object/Array/Date/RegExp/Number/String/Function),每一种都需要有不同的测试用例,对于需求方来说,更关注的是模块在每个用例下运行的表现——甚至可以说,这样的模块是以需求为驱动的,即使一开始无法满足所有用例,只要有明确的用例需求,就能够迭代出正确的功能。

有没有这样的测试方法呢?答案是肯定的,那就是 BDD

BDD

BDD(行为驱动开发 )是第二代的、由外及内的、基于拉(pull)的、多方利益相关者的(stakeholder)、多种可扩展的、高自动化的敏捷方法。它描述了一个交互循环,可以具有带有良好定义的输出(即工作中交付的结果):已测试过的软件。

BDD作为理论方法学,强调以需求为导向,并鼓励开发人员、QA与需求方之间的协作。BDD位于更宏观的位置,让开发者“做正确的事”;而TDD注重细节,确保开发者“正确的做事”。

BDD风格用例

describe('Array', function(){
  before(function(){
    // ...
  });

  describe('#indexOf()', function(){
    it('should return -1 when not present', function(){
      [1,2,3].indexOf(4).should.equal(-1);
    });
  });

  after(function(){ 
    // ...
  });
});

代码很易读,有点DSL的意思。常用的BDD接口有:

  • describe():描述场景,在里面可以设定Context,可包括多个测试用例,也可以嵌套场景
  • it():位于场景内,描述测试用例
  • before():所有测试用例的统一前置动作
  • after():所有测试用例的统一后置动作
  • beforeEach():每个测试用例的前置动作
  • afterEach():每个测试用例的后置动作

异步支持

describe('File loading', function () {
    it('content should not empty', function (done) {
       require('fs').read('test.txt', function(err, res){
           res.should.not.equal(null);
           done();
       });
    });
});

done()为异步方法完成回调,可用于下一用例的等待。

Mocha

MochaMocha 是一个优秀的JS测试框架,支持TDD/BDD,结合 should.js/expect/chai/better-assert,能轻松构建各种风格的测试用例。

此外,利用Mocha的reporter结合像istanbul 还能实现代码覆盖率报表的导出。

在Node项目中安装Mocha,需先在package.json中指定测试目录及包:

"scripts": {
    "test": "mocha --recursive --timeout 15000 -R spec --require should --harmony test/ --bail"
},
"dependencies": {
    "should": "*",
    "mocha": "*"
 }

然后使用npm install,随后便能使用npm test跑测试用例了。

实例

假设我的轮子是这个样子的:

module.exports.isObject = isObject;
module.exports.isDate = isDate;
module.exports.isString = isString;
module.exports.isNumber = isNumber;
module.exports.isFunction = isFunction;
module.exports.isRegExp = isRegExp;
module.exports.deepCopy = deepCopy;

function getObjectType(obj) {
    return Object.prototype.toString.call(obj);
}
function isObject(obj) {
    return getObjectType(obj) === '[object Object]';
}
function isDate(obj) {
    return getObjectType(obj) === '[object Date]';
}
function isString(obj) {
    return getObjectType(obj) === '[object String]';
}
function isArray(obj) {
    return getObjectType(obj) === '[object Array]';
}
function isNumber(obj) {
    return getObjectType(obj) === '[object Number]';
}
function isFunction(obj) {
    return getObjectType(obj) === '[object Function]';
}
function isRegExp(obj){
    return getObjectType(obj) === '[object RegExp]';
}
function deepCopy(obj) {
    var cloneObj = null;
    if (isArray(obj))
        cloneObj = [];
    else if (isObject(obj))
        cloneObj = {};
    else if (isDate(obj))
        cloneObj = new Date(obj.toJSON());
    else if (isRegExp(obj))
        cloneObj = new RegExp(obj.valueOf());
    else
        cloneObj = obj;
    for (var key in obj) {
        if(obj.hasOwnProperty(key)) {
            var child = obj[key];
            if (isObject(child) || isArray(child))
                cloneObj[key] = deepCopy(child);
            else if (isNumber(child) ||
                isString(child) ||
                isFunction(child))
                cloneObj[key] = child;
        }
    }
    return cloneObj;
}

 

构造一个复杂的对象,来测测轮子到底行不行:

var copyUtils = require('node-deepcopy');
var deepCopy = copyUtils.deepCopy,
    isFunction = copyUtils.isFunction,
    isRegExp = copyUtils.isRegExp;
var toValue = function(obj){
    return isFunction(obj) || isRegExp(obj) ? obj.toString() : JSON.stringify(obj);
};
describe('deep copy of the Complex Object', function () {
    var foo = function () {
        this.c = 3;
        this.a = [
            {e: 2, f: 'good', g: [1, 2, 3]}
        ];
        this.b = 'b';
        this.d = function () {
            console.log("I'm foo.d.")
        };
    };
    it("duplication should equal to the source", function () {
        var h = new foo();
        var cloned2 = deepCopy(h);
        toValue(cloned2).should.equal(toValue(h));
    });
    it("duplication should not equal to the source after modifying", function () {
        var h = new foo();
        var cloned2 = deepCopy(h);
        cloned2.a[0].e = 5;
        cloned2.a[0].f = '666';
        toValue(cloned2).should.not.equal(toValue(h));

        cloned2.a[0].g.splice(0, 2);
        toValue(h.a[0].g).should.not.equal(toValue(cloned2.a[0].g));
    });
});

npm test跑一下,可以看到测试通过:

BDD testing success

如果在这一步遇到什么问题,则需要根据场景和用例反向分析代码,并进行修复。在现实情况中,这个顺序也可能是倒过来的,先有BDD用例,然后才是匹配用例行为的代码。

 

更多文章请移步我的blog新地址: http://www.moye.me/