当前位置:嗨网首页>书籍在线阅读

08-其他的测试框架

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

11.2.3 其他的测试框架

前面也提到了,除了Nodeunit之外,还有另外几个测试框架可供Node开发者们使用。有些工具会简单点,每个工具也都有自己的优势和劣势。下一步,我会简要地介绍2种框架:Mocha和Vows。

1.Mocha

使用npm来安装Mocha:

npm install mocha –g

Mocha被认为是另一个很流行的测试框架——Espresso的继承者。

Mocha在浏览器和Node程序中都可以使用。它可以通过 done 方法来支持异步测试。对于同步测试来说,这个方法可以忽略。Mocha可以和所有的断言库结合使用。

下面是一段使用Assert模块的Mocha测试:

assert = require('assert')
describe('MyTest', function() {
  describe('First', function() {
    it('sample test', function() {
      assert.equal('hello','hello');
    });
  });
});

使用下面的命令运行测试:

mocha testcase.js

测试结果应该是成功的:

MyTest 
  First 
    ✓ sample test 
1 passing (15ms)

2.Vows

Vows是一个行为驱动开发(BDD)的测试框架。相对于其他框架而言它有一个优势:有更好理解的文档。测试是由套件(suite)组成的,而套件是由一系列顺序执行的测试组成的。一个组(batch)有一个或多个并行执行的上下文(context)组成,而每个上下文都包含一个标题(topic)。代码中的测试被定义为誓言(vow)。Vows引以为豪的就是它明确地区分了被测试的对象(标题)和实际测试(誓言)。

我知道上面这句话你可能每个字都懂但是连起来就不明白了,我们来看个例子,你就知道Vows是如何工作的了。首先,当然是安装Vows:

npm install vows

要使用Vows,需要使用一个简单的circle模块,这个模块可以用来计算圆形的面积和周长。因为返回值是浮点数,而我要测试相等性,所以必须将返回值四舍五入到4位小数:

const PI = Math.PI;
exports.area = function (r) {
  return (PI * r * r).toFixed(4);
}; 
exports.circumference = function (r) {
  return (2 * PI * r).toFixed(4);
};

在Vows测试程序中,circle对象就是我们所说的标题(topic),面积和周长就是我们所说的誓言(vow)。这二者都被封装到一个Vows上下文(context)中。套件(suite)则是整个测试程序,组(batch)就是测试用例(也就是circle和它的两个方法)。完整的测试如例11-2所示。

例11-2 包含一个组、一个上下文、一个标题和两个誓言的Vows测试

var vows = require('vows'),
    assert = require('assert');
var circle = require('./circle');
var suite = vows.describe('Test Circle');
suite.addBatch({
    'An instance of Circle': {
        topic: circle,
        'should be able to calculate circumference': function (topic) {
            assert.equal (topic.circumference(3.0), 18.8496);
        },
        'should be able to calculate area': function(topic) {
            assert.equal (topic.area(3.0), 28.2743);
        }
    } 
}).run();

由于 addBatch 方法的末尾调用了 run 方法,所以使用Node运行这个程序,就会运行其中的测试:

node vowstest.js

运行结果是两个成功的测试结果:

·· ✓ OK » 2 honored (0.012s)

标题要么是一个异步函数,要么是一个值。借助函数闭包的特性,我就可以直接从对象引用这两个函数作为标题,而不需要借助 circle 对象:

var vows = require('vows'),
    assert = require('assert');
var circle = require('./circle');
var suite = vows.describe('Test Circle');
suite.addBatch({
    'Testing Circle Circumference': {
        topic: function() { return circle.circumference;},
        'should be able to calculate circumference': function (topic) {
            assert.equal (topic(3.0), 18.8496);
        },
    },
    'Testing Circle Area': {
        topic: function() { return circle.area;},
        'should be able to calculate area': function(topic) {
            assert.equal (topic(3.0), 28.2743);
        }
    }
}).run();

在这个版本中,每个上下文都是一个有名称的对象: Testing Circle CircumferenceTesting Circle Area 。每个上下文中都有一个标题和一个誓言。

你还可以使用多个组,每个组中都包含多个上下文,而每个上下文中又可以包含多个标题和多个誓言。