mocha
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMocha
Mocha
Mocha is a flexible JavaScript test framework. Unlike Jest, it does not come with an assertion library, mocking, or snapshotting built-in. It is a runner that allows you to choose your own tools (usually Chai + Sinon).
Mocha是一款灵活的JavaScript测试框架。与Jest不同,它不内置断言库、模拟或快照功能。它是一个测试运行器,允许你选择自己的工具(通常搭配Chai + Sinon)。
When to Use
适用场景
- Flexibility: You want to pick your assertion library (Chai, Should.js).
- Node.js Backends: standard in many Express/NestJS (legacy) setups.
- Asynchronous Testing: Historically strong support for async (though standard now).
- 灵活性需求:你希望自行选择断言库(如Chai、Should.js)。
- Node.js后端:在许多Express/NestJS(传统)项目中是标准配置。
- 异步测试:历来对异步操作支持出色(如今已成为通用特性)。
Quick Start
快速开始
javascript
// npm install --save-dev mocha chai
const assert = require("chai").assert;
describe("Array", function () {
describe("#indexOf()", function () {
it("should return -1 when the value is not present", function () {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
});javascript
// npm install --save-dev mocha chai
const assert = require("chai").assert;
describe("Array", function () {
describe("#indexOf()", function () {
it("should return -1 when the value is not present", function () {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
});Core Concepts
核心概念
BDD Interface
BDD接口
describeitbeforeafterbeforeEachafterEachdescribeitbeforeafterbeforeEachafterEachHooks
钩子函数
Mocha allows defining hooks at the root level or inside suites to set up/tear down environments.
Mocha允许在根级别或测试套件内定义钩子函数,用于环境的搭建与销毁。
Async support
异步支持
Use in the block callback.
async/awaititjavascript
it("should save user", async function () {
const user = new User("tobi");
await user.save();
});在块的回调函数中使用。
itasync/awaitjavascript
it("should save user", async function () {
const user = new User("tobi");
await user.save();
});Best Practices (2025)
2025年最佳实践
Do:
- Use and
.only: Useful during development to run a single test (.skip).it.only(...) - Use (Istanbul): For code coverage (since Mocha doesn't have it built-in).
nyc
Don't:
- Don't use arrow functions () if you need
() => {}orthis.timeout(). Mocha binds the test context tothis.slow().this
建议:
- 使用和
.only: 开发期间可用于仅运行单个测试(.skip)。it.only(...) - 使用nyc(Istanbul): 用于代码覆盖率统计(因为Mocha本身不内置该功能)。
不建议:
- 不要使用箭头函数 (),如果你需要使用
() => {}或this.timeout()。Mocha会将测试上下文绑定到this.slow()上。this