前言

简单记录下单元测试和覆盖率测试的方法
对于Express框架的测试和覆盖率测试完全适用

安装与使用

  • 安装
    1
    $ npm i -g mocha
  • 使用
  1. 命令行执行

    1
    2
    3
    4
    5
    # 执行当前目录下的.test文件
    $ mocha

    # 递归执行当前目录下的.test文件(包括子文件)
    $ mocha --recursive
  2. 配置文件执行(mocha默认配置文件 mocha.opts)

参考文档

1
2
3
4
5
6
test/dir // 指定目录
--reporter tap // 指定报告文档格式
--recursive // 递归执行目录下的测试文件
--watch // 检查文件自动执行
--bail // 报错后是否自动执行
...
  1. 在node中添加插件,搭配覆盖测试cover(nyc)
    1
    2
    3
    4
    "scripts": {
    "test": "mocha --exit",
    "coverTest": "nyc --reporter html --reporter text npm run test"
    },

代码

搭配Express框架使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const assert = require('assert');
const { describe, it } = require("mocha");
const toolkit = require('../help/toolkit');
const request = require('supertest'); // 请求测试库

// 搭建express环境
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ limit: '10mb', extended: false }));
// 注册路由
app.get('/', (req, res) => res.send('Hello World!'));
app.get('/get', (req, res) => res.send(`Hello ${req.query.name}!`));
app.post('/post', (req, res) => res.send({msg: `Hello ${req.body.name}!`}));
app.listen(4567, () => console.log('Test listening port 4567'));

const url = 'http://127.0.0.1:4567';

describe('basic 测试', function () {
it('strictEqual', async function () {
// console.log('不抛出错误即为测试通过!')
assert.strictEqual(1, 1, '不相等'); // === 出错时返回message
// throw new Error('测试失败');
});
it('notStrictEqual', async function () {
assert.notStrictEqual(1, 2); // !==
});
it('ok', async function () {
assert.ok(true); // 判断是否为true
});
it('ok', async function () {
assert.ok(1); // 判断是否为true
});
it('throws', async function () {
assert.throws(() => {
throw new Error('throw error'); // 是否抛出错误
})
});
it('doesNotThrow', async function () {
assert.doesNotThrow(() => {
let a = 123;
})
});
it('deepStrictEqual', async function () {
const person1 = { "name":"jane", "age":"19" };
const person2 = { "name":"jane", "age":"19" };
assert.deepStrictEqual(person1, person2) // 是否深度相同 json
});
it('notDeepStrictEqual', async function () {
const person1 = { "name":"jaae", "age":"22" };
const person2 = { "name":"jane", "age":"19" };
assert.notDeepStrictEqual(person1, person2)
});
});

describe('HTTP 测试', function () {
const name = 'World';
it('get', async function () {
const res = await toolkit.get(`${url}/get?name=${name}`);
assert.strictEqual(res.body, 'Hello World!');
});
it('post', async function () {
const res = await toolkit.post(url, '/post', { name });
assert.strictEqual(res.body.msg, 'Hello World!');
});
// supertest请求测试库
it('request GET', function (done) {
request(url)
.get('/get?name=World')
.expect('Hello World!', done)
});
it('request POST', function (done) {
request(url)
.post('/post')
.send({name}) // x-www-form-urlencoded upload
// .set('Accept', 'application/json')
.expect(function(res) {
// console.log('res', res.body);
// 这里可以修改返回的内容
// done('err') 可以手动抛出错误
// done('1641564646');
// res.body.id = 'some fixed id';
})
.expect(200, {
msg: 'Hello World!',
}, done);
});
});