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

什么是Mocha

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

简单测试

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

//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断言在测试用例经过时控制台没有输出信息,只有错误时才会输出json

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

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

安装Mocha

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

// 全局安装  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就是其中一个。ui

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

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

性能测试

使用了单元覆盖率会使咱们的代码在正确性上获得必定保证,但在平常测试中,但好有一个问题要考虑,那就是性能。有一些辅助工具能够帮咱们达到目的,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”,稍等几秒便可看到结果,如图所示:

相关文章
相关标签/搜索