mocha测试接口类型及测试报告收集

时间:2023-03-09 15:48:34
mocha测试接口类型及测试报告收集

记录参考:

参考文档:

测试报告以及es6:

http://www.ruanyifeng.com/blog/2015/12/a-mocha-tutorial-of-examples.html

测试接口类型:

https://blog.****.net/hustzw07/article/details/73920809

参数

之前我们写 Mocha测试用例的时候,主要用 describe(), it() 组织用例。这跟 Jasmine 风格是类似的。实际上,这只是 Mocha 支持的一种而已。

在命令行中,有如下命令可供我们选择。

  1. -u, --ui <name>  specify user-interface (bdd|tdd|qunit|exports)

默认情况下,Mocha使用 bdd 帮我们执行 describe(), it() 的用例。

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

我们也可以选择其他接口类型。比如 tdd。
Mocha的测试接口类型指的是集中测试用例组织模式的选择,更像是为用户提供几种组织测试用例的方式。

BDD

BDD行为驱动开发,全名 Behavior Driven Development。
Mocha默认的测试接口。 BDD测试接口提供 describe(), context(), it(), specify(), before(), after(), beforeEach(), 和 afterEach()几种函数,其中context函数只是describe函数的别名,specify函数也是it函数的别名。

另外,Jasmine的测试风格就是bdd,它的特征就是使用describe,it。 对 BDD 有兴趣的可以去这个网站看下
http://jbehave.org/introduction.html

TDD

TDD,测试驱动开发(Test-Driven Development)
TDD接口提供 suite(), test(), suiteSetup(), suiteTeardown(), setup(), 和 teardown()函数,用例写法如下:

  1. suite('#indexOf()', function(){
  2. test('should return -1 when not present', function(){
  3. ([1,2,3].indexOf(4)).should.be.eql(-1);
  4. });
  5. });

tdd跟bdd区别在于,它使用suite,test,suiteSetup,suiteTeardown,setup,teardown 等函数。

Exports

exports 跟 node 里的模块语法很像,before, after, beforeEach, and afterEach 都是作为对象的属性,其它对象的值默认是 suite,属性是函数的话,代表是一个test。简单来说,除了钩子函数,对象是 测试集, 属性是 测试用例。

  1. require("should");
  2. module.exports = {
  3. before: function(){
  4. // ...
  5. },
  6. 'Array': {
  7. '#indexOf()': {
  8. 'should return -1 when not present': function(){
  9. [1,2,3].indexOf(4).should.equal(-1);
  10. }
  11. }
  12. }
  13. };

钩子函数

从 BDD 到 TDD,describe 和 it 变变成了 suite, test。对应的钩子函数也变了。那它们的行为有没有改变呢?下面是个例子。

  1. var assert = require('assert');
  2. var mocha  = require('mocha');
  3. require("should");
  4. suite('Array', function(){
  5. suiteSetup(function(){
  6. console.log();
  7. console.log('-----------suiteSetup');
  8. });
  9. suiteTeardown(function(){
  10. console.log('-----------suiteTeardown');
  11. console.log();
  12. });
  13. setup(function(){
  14. console.log();
  15. console.log('-----------setup');
  16. });
  17. teardown(function(){
  18. console.log('-----------teardown');
  19. console.log();
  20. });
  21. test('First layer', function(){
  22. ([1,2,3].indexOf(4)).should.eql(-1);
  23. });
  24. suite('Second layer', function(){
  25. suiteSetup(function(){
  26. console.log();
  27. console.log('-----------Second layer suiteSetup');
  28. });
  29. setup(function(){
  30. console.log();
  31. console.log('-----------Second layer setup');
  32. });
  33. test('Second layer test', function(){
  34. ([1,2,3].indexOf(4)).should.eql(-1);
  35. });
  36. });
  37. });

输出

mocha测试接口类型及测试报告收集