chai

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Chai

Chai

Chai is an assertion library. It pairs naturally with Mocha. It supports TDD (
assert
) and BDD (
expect
,
should
) styles.
Chai是一款断言库,天然适配Mocha测试框架。它支持TDD(
assert
)和BDD(
expect
should
)两种风格。

When to Use

适用场景

  • With Mocha: The default pair.
  • Expressive Tests: You want tests to read like English ("expect foo to be a string").
  • 搭配Mocha使用:这是默认的经典组合。
  • 编写表意清晰的测试用例:你希望测试代码读起来像自然英语(例如“expect foo to be a string”可理解为“期望foo是一个字符串”)。

Quick Start

快速开始

javascript
import { expect } from "chai";

const foo = "bar";
const beverages = { tea: ["chai", "matcha", "oolong"] };

expect(foo).to.be.a("string");
expect(foo).to.equal("bar");
expect(foo).to.have.lengthOf(3);
expect(beverages).to.have.property("tea").with.lengthOf(3);
javascript
import { expect } from "chai";

const foo = "bar";
const beverages = { tea: ["chai", "matcha", "oolong"] };

expect(foo).to.be.a("string");
expect(foo).to.equal("bar");
expect(foo).to.have.lengthOf(3);
expect(beverages).to.have.property("tea").with.lengthOf(3);

Core Concepts

核心概念

Styles

风格

  • Assert: Classic.
    assert.equal(foo, 'bar')
    .
  • Expect: BDD. Chainable.
    expect(foo).to.be.equal('bar')
    .
  • Should: BDD. Extends Object prototype.
    foo.should.be.equal('bar')
    . (Less common now due to side effects).
  • Assert:经典风格。写法如
    assert.equal(foo, 'bar')
  • Expect:BDD风格,支持链式调用。写法如
    expect(foo).to.be.equal('bar')
  • Should:BDD风格,通过扩展Object原型实现。写法如
    foo.should.be.equal('bar')
    。(如今因存在副作用,使用已较少)

Plugins

插件

Chai has a rich ecosystem.
  • chai-http
    : For API testing.
  • chai-as-promised
    : For asserting promises (
    return expect(promise).to.eventually.equal(2)
    ).
Chai拥有丰富的生态系统。
  • chai-http
    :用于API测试。
  • chai-as-promised
    :用于断言Promise(示例写法:
    return expect(promise).to.eventually.equal(2)
    )。

Best Practices (2025)

2025年最佳实践

Do:
  • Stick to one style: Usually Expect. It's clean and doesn't modify prototypes.
  • Use Descriptive Chains:
    to.be.true
    reads better than
    to.equal(true)
    .
Don't:
  • Don't mix Assert and Expect: Confuses the reader.
建议做法
  • 坚持使用单一风格:通常推荐Expect风格,它代码简洁且不会修改对象原型。
  • 使用表意明确的链式调用
    to.be.true
    to.equal(true)
    的可读性更强。
不建议做法
  • 不要混合使用Assert和Expect风格:这会让阅读者产生困惑。

References

参考资料