mocha的使用总结

一.mocha的安装和运行

1.安装:

# 1.可以全局安装
npm install -g mocha

# 2.也可以在项目中安装
npm install -D mocha
复制代码

2.测试启动命令

  • 使用如下的命令时,mocha会默认执行当前路径的test/目录下的所有测试文件
# 1.若mocha是全局安装的
mocha

# 2.若mocha是在项目中安装的
node_module\mocha\bin\mocha
复制代码

3.项目目录结构:

在项目下新建一个test/目录,为默认的测试文件存放位置

my_project/
—— hello.js                 // 含有待测试内容的文件
—— test/                    // test/目录存放所有的测试文件
———— hello_test.js              // 测试文件
———— ...                        // ...
—— package.json             // 项目描述文件
—— node_modules/            // npm安装包
复制代码

二.mocha测试文件的基本写法:

一个测试文件的内容主要写法有三部分:

  1. describe(groupName, callback)测试分组describe可以多层嵌套使用
  2. it('testItemName', callback)测试项
    • 注意:
      • 测试同步函数时,callback内无需传入参数
      • 测试异步函数时,callback内需要传入一个参数,通常命名为done
  3. 断言:对测试内容的判断,断言是否满足
    • 默认使用的是Node.js的assert模块
    • 也可以自己选择其他的断言库:
      • 断言库列表:
        • should.jsshould语法风格BDD风格)的断言库
        • expect.jsexpect语法风格简约BDD风格)的断言库
        • chai:可自由在(assert()should()expect())三种风格进行选择的断言库
        • better-assert:~
        • unexpected: ~
      • 第三方断言库的使用方法:
        1. 方式1:在每个测试文件中都使用require引入断言库依赖,然后即可在当前的测试文件中使用了
        2. 方式2:在test/目录下添加一个mocha.opts配置文件,在里面写入要使用的断言库,之后即可在所有的测试文件中直接使用了,例如:
        // test/mocha.opts
        --require should
        复制代码

示例:

// hello.js
module.exports = function (...rest) {
    var sum = 0;
    for (let n of rest) {
        sum += n;
    }
    return sum;
};
复制代码
// test/hello.test.js
const assert = require('assert');
const sum = require('../hello');

describe('#hello.js', () => {
    describe('#sum()', () => {
        it('sum() should return 0', () => {
            assert.strictEqual(sum(), 0);
        });
        it('sum(1) should return 1', () => {
            assert.strictEqual(sum(1), 1);
        });
        it('sum(1, 2) should return 3', () => {
            assert.strictEqual(sum(1, 2), 3);
        });
        it('sum(1, 2, 3) should return 6', () => {
            assert.strictEqual(sum(1, 2, 3), 6);
        });
    })
})
复制代码

命令行输入mocha开启测试,控制台输出如下的结果,说明编写的4个测试项全部通过了

#hello.js
    #sum()
      ✓ sum() should return 0
      ✓ sum(1) should return 1
      ✓ sum(1, 2) should return 3
      ✓ sum(1, 2, 3) should return 6
  4 passing (7ms)
复制代码

三.mocha的高级用法:

1. mocha为每个测试组(describe)提供了如下几个钩子函数:

  1. before(fn)fn会在该组中的所有测试项被测试之前调用
  2. after(fn)fn会在该组中的所有测试项被测试之后调用
  3. beforeEach(fn)fn会在该组中每一个测试项被调用之前调用
  4. afterEach(fn)fn会在该组中每一个测试项被调用之前调用
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
  it('测试项1', () => {
      ...
  })
  it('测试项2', () => {
      ...
  })
});
复制代码

2.异步测试:

  1. 有如下一个异步函数需要进行测试:
// async.js
const fs = require('fs');

module.exports = async () => {
    let expression =await fs.readFile('./data.txt', 'utf-8');
    let fn = new Function('return ' + expression);
    let r = fn();
    console.log(`Calculate: ${expression} = ${r}`);
    return r;
}
复制代码
// data.txt
1 + (2 + 4) * (9 - 2) / 3
复制代码
  1. 对于异步函数的测试,it(测试项名, callback(done) {...})callback中需要传入一个done参数
    • 若异步测试通过,则在callback内部手动调用done()
    • 若异步测试不通过,则在callback内部手动调用done(err)

    ps:针对不同写法的异步函数,其对应的测试写法也有所不同:

// async-test.js
const assert = require('assert');
const hello = require('../hello.js');

describe('#async hello', () => {
  describe('#asyncCalculate()', () => {
    
    // 1.如果待测试的异步函数是回调函数语法的,则必须在回调函数中来进行测试判断(写法麻烦) 
    it('test async function', function(done) {
        fs.readFile('filepath', function (err, data) {
            if (err) {
                done(err);
            } else {
                done();
            }
        });  
    })
    
    // 2.如果待测试的异步函数是async/await 语法的,可通过try catch来测试判断(写法还是比较麻烦)
    it('#test async function', (done) => {
        (async function () {
            try {
                let r = await hello();
                assert.strictEqual(r, 15);
                done();
            } catch (err) {
                done(err);
            }
        })();
    });

    // 3.待测试的异步函数是async/await语法的,最简单的写法——把async函数当作同步函数来测试!!!
    it('test async function', async () => {
        let r = await hello();
        assert.strictEqual(r, 15);
    })
  })  
})
复制代码
  • 总结: 对于异步函数的测试,若异步函数是使用的async\await关键字,其在编写测试用例时很简单,基本跟同步函数的测试用例写法一样

转载于:https://juejin.im/post/5c8cec225188257c5b4787a9

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值