Mocha 配置
describe / it / before / after
const assert = require('assert');
const { UserService } = require('../src/UserService');
describe('UserService', function () {
let service;
let db;
before(async function () {
// 在套件所有测试之前运行一次
db = await connectTestDB();
});
after(async function () {
await db.close();
});
beforeEach(async function () {
service = new UserService(db);
await db.seed([{ id: 1, name: '张三' }]);
});
afterEach(async function () {
await db.clearAll();
});
it('按 id 查找用户', async function () {
const user = await service.findById(1);
assert.strictEqual(user.name, '张三');
});
it('未知 id 返回 null', async function () {
const user = await service.findById(999);
assert.strictEqual(user, null);
});
});
.mocharc.yml / .mocharc.json
# .mocharc.yml
spec: 'test/**/*.test.js'
require:
- '@babel/register'
- 'test/helpers/setup.js'
timeout: 5000
retries: 2
reporter: spec
color: true
recursive: true
exit: true
# 并行执行
parallel: true
jobs: 4
报告器
# 内置报告器
mocha --reporter spec # 默认:详细输出
mocha --reporter dot # 最简点号
mocha --reporter tap # TAP 协议
mocha --reporter json # JSON 输出
# 第三方报告器
npm install mocha-junit-reporter
mocha --reporter mocha-junit-reporter \
--reporter-options mochaFile=results/junit.xml
npm install mochawesome
mocha --reporter mochawesome \
--reporter-options reportDir=report,inline=true
超时与重试
describe('API 测试', function () {
this.timeout(10000); // 套件超时设置
it('获取数据', async function () {
this.timeout(3000); // 单个测试超时
const data = await fetchData();
assert.ok(data);
});
it('不稳定网络测试', async function () {
this.retries(3); // 最多重试 3 次
const result = await unstableService.call();
assert.strictEqual(result.status, 'ok');
});
it.skip('尚未实现', function () { });
});
根钩子与全局 Fixtures
// test/hooks.js — 根钩子插件
exports.mochaHooks = {
async beforeAll() {
await startMockServer();
},
async afterAll() {
await stopMockServer();
},
};
// test/fixtures.js — 全局 fixtures(Mocha v8+)
exports.mochaGlobalSetup = async function () {
process.env.TEST_DB_URL = await startTestDatabase();
};
exports.mochaGlobalTeardown = async function () {
await stopTestDatabase();
};
ESM 支持
// .mocharc.yml 配置 ESM
spec: 'test/**/*.test.mjs'
// test/math.test.mjs
import assert from 'node:assert/strict';
import { add } from '../src/math.mjs';
describe('数学运算', () => {
it('加法', () => {
assert.equal(add(2, 3), 5);
});
});
// package.json
{
"scripts": {
"test": "mocha",
"test:watch": "mocha --watch",
"test:coverage": "c8 mocha"
}
}