mocha

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Mocha

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接口

describe
(suite),
it
(test),
before
,
after
,
beforeEach
,
afterEach
.
describe
(测试套件)、
it
(测试用例)、
before
after
beforeEach
afterEach

Hooks

钩子函数

Mocha allows defining hooks at the root level or inside suites to set up/tear down environments.
Mocha允许在根级别或测试套件内定义钩子函数,用于环境的搭建与销毁。

Async support

异步支持

Use
async/await
in the
it
block callback.
javascript
it("should save user", async function () {
  const user = new User("tobi");
  await user.save();
});
it
块的回调函数中使用
async/await
javascript
it("should save user", async function () {
  const user = new User("tobi");
  await user.save();
});

Best Practices (2025)

2025年最佳实践

Do:
  • Use
    .only
    and
    .skip
    : Useful during development to run a single test (
    it.only(...)
    ).
  • Use
    nyc
    (Istanbul)
    : For code coverage (since Mocha doesn't have it built-in).
Don't:
  • Don't use arrow functions (
    () => {}
    ) if you need
    this.timeout()
    or
    this.slow()
    . Mocha binds the test context to
    this
    .
建议:
  • 使用
    .only
    .skip
    : 开发期间可用于仅运行单个测试(
    it.only(...)
    )。
  • 使用nyc(Istanbul): 用于代码覆盖率统计(因为Mocha本身不内置该功能)。
不建议:
  • 不要使用箭头函数 (
    () => {}
    ),如果你需要使用
    this.timeout()
    this.slow()
    。Mocha会将测试上下文绑定到
    this
    上。

References

参考资料