Mocha 是一个功能丰富、灵活的 JavaScript 测试框架,主要用于在 Node.js 和浏览器环境中运行测试用例。它以简单性、异步支持强大和可扩展性著称,常与断言库(如 Chai、Node.js 内置的 assert
)结合使用。
以下是 Mocha 的核心用法和关键概念详解:
使用 npm 或 yarn 安装 Mocha:
npm install --save-dev mocha
# 或
yarn add --dev mocha
创建一个测试文件(如 test.js
),使用 Mocha 提供的 describe
和 it
组织测试:
const assert = require('assert');
// 测试套件 (Test Suite)
describe('Array 测试', function() {
// 单个测试用例 (Test Case)
it('应返回 -1 当元素不在数组中', function() {
assert.strictEqual([1, 2, 3].indexOf(4), -1);
});
});
在 package.json
中添加脚本:
{
"scripts": {
"test": "mocha"
}
}
然后执行:
npm test
默认会运行 test
目录下的所有 .js
文件。也可指定文件:
npx mocha test.js
用于测试前置/后置操作:
before()
: 整个套件开始前执行一次beforeEach()
: 每个测试用例开始前执行afterEach()
: 每个测试用例结束后执行after()
: 整个套件结束后执行describe('数据库测试', function() {
before(() => console.log('连接数据库'));
after(() => console.log('断开数据库'));
beforeEach(() => console.log('初始化数据'));
afterEach(() => console.log('清理数据'));
it('测试查询操作', () => { /* ... */ });
});
Mocha 通过三种方式处理异步:
done
)it('异步测试 (callback)', function(done) {
setTimeout(() => {
assert.ok(true);
done(); // 调用 done 表示测试完成
}, 100);
});
it('异步测试 (Promise)', function() {
return fetchData() // 直接返回 Promise
.then(data => assert.equal(data.status, 200));
});
it('异步测试 (async/await)', async function() {
const data = await fetchData();
assert.strictEqual(data.id, 1);
});
避免在钩子和测试用例中使用箭头函数!它们会破坏 Mocha 的上下文(this
),导致无法访问共享状态:
describe('错误示例', () => {
before(() => {
this.timeout(1000); // ❌ 错误!箭头函数中 this 指向错误
});
});
使用 --reporter
指定输出格式:
npx mocha --reporter dot
常用格式:spec
(默认)、dot
、nyan
、tap
。
通过 mocha.opts
或 package.json
配置:
# mocha.opts
--reporter dot
--timeout 5000
--recursive # 递归搜索子目录
或在 package.json
中:
{
"mocha": {
"timeout": 5000,
"recursive": true
}
}
const { expect } = require('chai');
it('使用 Chai 做断言', () => {
expect([1, 2]).to.be.an('array').that.includes(2);
});
it('应抛出错误', function() {
expect(() => { throw new Error('fail') }).to.throw('fail');
});
describe('功能A', function() {
it.skip('待实现测试', () => { /* 跳过 */ }); // 跳过
it.only('重点测试', () => { /* 仅运行此测试 */ }); // 仅运行
});
在浏览器中运行测试(需引入 mocha.css
和 mocha.js
):
Mocha 的核心优势在于:
describe
/it
层次对于新项目,建议:
describe
/it
组织测试async/await
处理异步beforeEach
管理测试状态是否需要更深入探讨某些特定功能(如TDD/BDD模式、集成测试覆盖率工具Istanbul等)?