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

什么是Mocha

Mocha是一个功能丰富的,运行在node.js上的JavaScript的测试框架。

简单测试

(1)在没有引入测试框架前的测试代码

//math.js
module.exports = {
    add : (...args) =>{
        return args.reduce((prev,curr)=>{
           return prev + curr +1;
        })
    },

    mul:(...args) =>{
        return args.reduce((prev,curr) =>{
            return prev * curr
        })
    }
}

//test.js
const {add ,mul} = require('./math');

if(add(2,3)===5){
    console.log('add(2,3)===5');
}else{
    console.log('add(2,3)!==5');
}

(2)引用node assert模块的测试
上面的测试用例不具有语义化的特点,而通过断言库我们可以达到语义化测试用例的目的。
注:assert断言在测试用例通过时控制台没有输出信息,只有错误时才会输出

const   assert = require('assert');
const {add ,mul} = require('./math');
assert.equal(add(2,3),6); 

除了node的assert的模块,也有一些第三方断言库可以使用,例如Chai

安装Mocha

Mocha本身是没有断言库的,如果在测试用例中引入非node自带的语言库需要自己安装。

// 全局安装  Install with npm globally
npm install --global mocha
// 本地安装 as a development dependency for your project
npm install --save-dev mocha

使用Mocha

const {should,expect,assert} = require('chai');
const {add,nul} = require('./math');
describe('#math',()=>{
    describe('add',()=>{
        it('should return 5 when 2 + 3',() =>{
            expect(add(2,3),5);
        });
        
        it('should return -1 when 2 + -3',() =>{
            expect(add(2,-3),-1);
        })   
     })

     describe('mul',()=>{
        it('should return 6 when 2 * 3',() =>{
            expect(add(2,3),6);
        });
    });
})

运行Mocha,可以通过在package.json中通过配置运行

{
      //其它配置...
       "scripts": {
        "test": "mocha mocha.js"
  }
}

然后执行“npm test”命令即可,需要注意的是mocha会检查统一路径下的所有文件,所以在在配置时可以指定到特定的某个文件,以免报错。执行完之后会把结果(无论对错和执行测试用例的数量还有执行总时长)显示出来,如下图所示:

mocha其它功能实例

//只执行其中某条用例
it.only('should return 5 when 2 + 3',() =>{
            expect(add(2,3),5);
      });
//跳过某条不执行
it.skip('should return 5 when 2 + 3',() =>{
            expect(add(2,3),5);
 });

测试的覆盖率

以上我们系的例子代码量都比较少,仅作为示例,但如果代码量庞大,我们怎样保证测试的覆盖率呢,这就需要一些工具来帮我们检测,istanbul就是其中一个。

//安装istanbul
npm install -g istanbul
  {
      //其它配置...
    "scripts": {
    "test": "mocha mocha.js",
    "cover":"istanbul cover _mocha mocha.js"
  }
}

运行stanbul来检测代码的覆盖率,可以通过在package.json中通过来配置。然后通过“npm run cover”这条命令来调用,结果如图所示:

性能测试

使用了单元覆盖率会使我们的代码在正确性上得到一定保证,但在日常测试中,但好有一个问题要考虑,那就是性能。有一些辅助工具可以帮我们达到目的,benchmark就是其一。

npm i --save benchmark
//fn.js
module.exports = {
    num1:n =>parseInt(n),
    num2:n => Number(n)
}
//benchmark.js
const {num1,num2} = require('./fn');

const Benchmark = require('benchmark');
const suite = new Benchmark.Suite;

suite.add('parseInt',() =>{
    num1('123456');
}).add('Number',() =>{
     num2('123456')
}).on('cycle',event =>{
     console.log(String(event.target))
}).on('complete',function(){
    console.log('Faster is '+ this.filter('fastest').map('name'));
}).run({
    async:true
});

然后在命令行执行“node benchmark”,稍等几秒即可看到结果,如图所示:

posted @ 2018-08-13 21:44  Julie在进化  阅读(7256)  评论(0编辑  收藏  举报