当前位置: 移动技术网 > IT编程>开发语言>JavaScript > NodeJs测试框架Mocha的安装与使用

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

2019年03月20日  | 移动技术网IT编程  | 我要评论

mocha是运行在nodejs和浏览器下的javascript的单元测试框架,官方文档在,相当的容易上手和好用,单元测试框架其实都差不多,基本都包含下面内容:

用于写测试用例的宏,属性或者函数
断定库, 用于测试是否可以通过
辅助库,如hook库(测试前后调用某些函数或者方法),异常检查(某些函数在某些参数的情况下抛出异常), 输入组合(支持多排列的参数输入组合)等。
支持ide的集成
下面就按照官方文档的顺序来简明扼要的

安装与初步的使用

在控制台窗口中执行下列命令:

$ npm install -g mocha
$ mkdir test
$ $editor test/test.js

可以写如下代码:

var assert = require('assert');
describe('array', function() {
 describe('#indexof()', function () {
  it('should return -1 when the value is not present', function () {
   assert.equal(-1, [1,2,3].indexof(5));
   assert.equal(-1, [1,2,3].indexof(0));
  });
 });
});

回到控制台:

$ mocha

 .

 ✔ 1 test complete (1ms)

这里mocha会查找当前文件目录下test文件夹下的内容,自动执行。

断定库

这个是判定测试用例是否通过,默认下可以用nodejs的assert库,与此同时,mocha支持我们使用不同的断定库,现在可以支持下面的断定库,每个断定库的用法有一些差异,自己可以参考相应的文档。

1 should.js() bdd style shown throughout these docs (bdd模式,本文档用的都是这个断定库)
2 better-assert() c-style self-documenting assert()(c-模型下的断定库)
3 expect.js (https://github.com/automattic/expect.js)expect() style assertions (expect模式的断定库)
4 unexpected() the extensible bdd assertion toolkit
5 chai() expect(), assert() and should style assertions

同步代码

同步代码表示测试的是同步函数,上面的array相关的例子代码就是。这个比较好理解。

异步代码

只所以有异步代码测试,原因是在nodejs上许多异步函数,如下面的代码中,只有done()函数执行完毕后,该测试用例才算完成

describe('user', function() {
 describe('#save()', function() {
  it('should save without error', function(done) {
   var user = new user('luna');
   user.saveasync(function(err) {
    if (err) throw err;
    done(); // 只有执行完此函数后,该测试用例算是完成。
   });
  });
 });
});

详解describe和it

上面的实例代码比较简单,那么什么是describe和it呢? 大致上,我们可以看出describe应该是声明了一个testsuit(测试集合) ,而且测试集合可以嵌套管理,而it声明定义了一个具体的测试用例。 以bdd interface为例,具体的源代码如下:

  /**
   * describe a "suite" with the given `title`
   * and callback `fn` containing nested suites
   * and/or tests.
   */
  context.describe = context.context = function(title, fn) {
   var suite = suite.create(suites[0], title);
   suite.file = file;
   suites.unshift(suite);
   fn.call(suite);
   suites.shift();
   return suite;
  };

   /**
   * describe a specification or test-case
   * with the given `title` and callback `fn`
   * acting as a thunk.
   */

  context.it = context.specify = function(title, fn) {
   var suite = suites[0];
   if (suite.pending) {
    fn = null;
   }
   var test = new test(title, fn);
   test.file = file;
   suite.addtest(test);
   return test;
  };

hooks(钩子)

实际上这个在写unit test是很常见的功能,就是在执行测试用例,测试用例集合前或者后需要某个回调函数(钩子)。mocha提供了before(),after(), beforeeach() 和afteteach(),示例代码如下:

describe('hooks', function() {
 before(function() {
  // runs before all tests in this block
  // 在执行所有的测试用例前 函数会被调用一次
 });

 after(function() {
  // runs after all tests in this block
  // 在执行完所有的测试用例后 函数会被调用一次
 });

 beforeeach(function() {
  // runs before each test in this block
   // 在执行每个测试用例前 函数会被调用一次
 });

 aftereach(function() {
  // runs after each test in this block
  // 在执行每个测试用例后 函数会被调用一次
 });

 // test cases
});

hooks还有下列其他用法:

describing hooks - 可以对钩子函数添加描述,能更好的查看问题
asynchronous hooks (异步钩子): 钩子函数可以是同步,也可以是异步的,和测试用例一下,下面是异步钩子的示例代码:

 beforeeach(function(done) {
  // 异步函数
  db.clear(function(err) {
   if (err) return done(err);
   db.save([tobi, loki, jane], done);
  });
 });

root-level hooks (全局钩子) - 就是在describe外(测试用例集合外)执行,这个一般是在所有的测试用例前或者后执行。
pending tests (挂起测试)

就是有一些测试,现在还没有完成,有点类似todo, 如下面的代码:

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函数的测试用例。
 tests.foreach(function(test) {
  it('correctly adds ' + test.args.length + ' args', function() {
   var res = add.apply(null, test.args);
   assert.equal(res, test.expected);
  });
 });
});

interfaces(接口)

mocha的接口系统允许用户用不同风格的函数或者样式写他们的测试用例集合和具体的测试用例,mocha有bdd,tdd,exports,qunit和require 风格的接口。

bdd - 这个是mocha的默认样式,我们在本文中的示例代码就是这样的格式。
其提供了describe(), context(), it(), before(), after(), beforeeach(), and aftereach()的函数,示例代码如下:

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

  describe('#indexof()', function() {
   context('when not present', function() {
    it('should not throw an error', function() {
     (function() {
      [1,2,3].indexof(4);
     }).should.not.throw();
    });
    it('should return -1', function() {
     [1,2,3].indexof(4).should.equal(-1);
    });
   });
   context('when present', function() {
    it('should return the index where the element first appears in the array', function() {
     [1,2,3].indexof(3).should.equal(2);
    });
   });
  });
 });

tdd - 提供了 suite(), test(), suitesetup(), suiteteardown(), setup(), 和 teardown()的函数,其实和bdd风格的接口类似(suite相当于describe,test相当于it),示例代码如下:

suite('array', function() {
 setup(function() {
  // ...
 });

 suite('#indexof()', function() {
  test('should return -1 when not present', function() { 
   assert.equal(-1, [1,2,3].indexof(4));
  });
 });
});

exports - 对象的值都是测试用例集合,函数值都是测试用例。 关键字before, after, beforeeach, and aftereach 需要特别定义。
具体的示例代码如下:

module.exports = {
 before: function() {
  // ...
 },

 'array': {
  '#indexof()': {
   'should return -1 when not present': function() {
    [1,2,3].indexof(4).should.equal(-1);
   }
  }
 }
};

qunit - 有点像tdd,用suit和test函数,也包含before(), after(), beforeeach()和aftereach(),但是用法稍微有点不一样, 可以参考下面的代码:

function ok(expr, msg) {
 if (!expr) throw new error(msg);
}

suite('array');

test('#length', function() {
 var arr = [1,2,3];
 ok(arr.length == 3);
});

test('#indexof()', function() {
 var arr = [1,2,3];
 ok(arr.indexof(1) == 0);
 ok(arr.indexof(2) == 1);
 ok(arr.indexof(3) == 2);
});

suite('string');

test('#length', function() {
 ok('foo'.length == 3);
});

require - 该接口允许我们利用require关键字去重新封装定义 describe ,it等关键字,这样可以避免全局变量。
如下列代码:

var testcase = require('mocha').describe;
var pre = require('mocha').before;
var assertions = require('mocha').it;
var assert = require('assert');

testcase('array', function() {
 pre(function() {
  // ...
 });

 testcase('#indexof()', function() {
  assertions('should return -1 when not present', function() {
   assert.equal([1,2,3].indexof(4), -1);
  });
 });
});

上述默认的接口是bdd, 如果想使用其他的接口,可以使用下面的命令行:

mocha -ui  接口(tdd|exports|qunit...)

reporters (测试报告/结果样式)

mocha 支持不同格式的测试结果暂时,其支持 spec, dot matrix,nyan,tap…等等,默认的样式为spec,如果需要其他的样式,可以用下列命令行实现:

mocha --reporter 具体的样式(dot matrix|tap|nyan...)

editor plugins

mocha 能很好的集成到textmate,wallaby.js,jetbrains(intellij idea, webstorm) 中,这里就用webstorm作为例子。 jetbrains提供了nodejs的plugin让我们很好的使用mocha和nodejs。 添加mocha 的相关的菜单,具体配置过程可以参考

这里就可以直接在webstorm中运行,调试mocha的测试用例了。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网