Mocha

Mocha 是一个功能强大的 JavaScript 测试框架,可以运行在和浏览器环境中

安装 Mocha:

1
$ npm install --save-dev mocha

使用 node 自带的断言模块 assert

1
2
3
4
5
6
7
const assert = require('assert');

describe('加法运算测试', function() {
it('1 + 1 等于 2', function() {
assert.equal(1 + 1, 2);
});
});

Chai:

使用功能更强大 Chai 断言库,支持 expect、assert 和 should 三种断言风格

安装 Chai:

1
$ npm install --save-dev chai
1
2
3
4
5
6
7
8
9
10
11
12
const expect = require('chai').expect;

describe('字符串测试', function() {
it('测试字符串 foo', function() {
let foo = 'foobar';
expect(foo).to.have.lengthOf(6);
expect(foo).to.be.a('string');
expect(foo).to.be.not.an.instanceof(String);
expect(foo).to.equal('foobar');
expect(foo).to.include('bar');
});
});

异步测试:

调用 done 回调函数

1
2
3
4
5
6
7
8
9
10
const expect = require('chai').expect;

describe('异步测试', function() {
it('测试 setTimeout', function(done) {
setTimeout(() => {
expect(1 + 1).to.be.equal(2);
done();
}, 1000);
});
});

钩子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const expect = require('chai').expect;

describe('hooks', function () {

it('1 + 1', function () {
expect(1 + 1).to.be.equal(2);
});

before(function () {
console.log('所有测试用例前运行');
});

beforeEach(function () {
console.log('每个测试用例前运行');
});

afterEach(function () {
console.log('每个测试用例后运行');
});

after(function () {
console.log('所有测试用例后运行');
});
});