NodeJs测试框架Mocha的安装与使用

2020-06-17 06:42:09易采站长站整理


describe('Array', function() {
describe('#indexOf()', function() {
// pending test below 暂时不写回调函数
it('should return -1 when the value is not present');
});
});

Exclusive Tests (排它测试)

排它测试就是允许一个测试集合或者测试用例,只有一个被执行,其他都被跳过。如下面测试用例集合:


describe('Array', function() {
describe.only('#indexOf()', function() {
// ...
});
// 测试集合不会被执行
describe('#ingored()', function() {
// ...
});
});

下面是对于测试用例:


describe('Array', function() {
describe('#indexOf()', function() {
it.only('should return -1 unless present', function() {
// ...
});
// 测试用例不会执行
it('should return the index when present', function() {
// ...
});
});
});

需要说明的是,对于Hooks(回调函数)会被执行。

Inclusive Tests(包含测试)

与only函数相反,skip函数,将会让mocha系统无视当前的测试用例集合或者测试用例,所有被skip的测试用例将被报告为Pending。
下面是对与测试用例集合的示例代码:


describe('Array', function() {
//该测试用例会被ingore掉
describe.skip('#indexOf()', function() {
// ...
});
// 该测试会被执行
describe('#indexOf()', function() {
// ...
});
});

下面例子是对具体的测试用例:


describe('Array', function() {
describe('#indexOf()', function() {
// 测试用例会被ingore掉
it.skip('should return -1 unless present', function() {
// ...
});
// 测试用例会被执行
it('should return the index when present', function() {
// ...
});
});
});

Dynamically Generating Tests(动态生成测试用例)

其实这个在很多其他的测试工具,如NUnit也会有,就是将测试用例的参数用一个集合代替,从而生成不同的测试用例。下面是具体的例子:


var assert = require('assert');

function add() {
return Array.prototype.slice.call(arguments).reduce(function(prev, curr) {
return prev + curr;
}, 0);
}

describe('add()', function() {
var tests = [
{args: [1, 2], expected: 3},
{args: [1, 2, 3], expected: 6},
{args: [1, 2, 3, 4], expected: 10}
];
// 下面就会生成三个不同的测试用例,相当于写了三个it函数的测试用例。