chai
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseChai
Chai
Chai is an assertion library. It pairs naturally with Mocha. It supports TDD () and BDD (, ) styles.
assertexpectshouldChai是一款断言库,天然适配Mocha测试框架。它支持TDD()和BDD(、)两种风格。
assertexpectshouldWhen 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. . (Less common now due to side effects).
foo.should.be.equal('bar')
- 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.
- : For API testing.
chai-http - : For asserting promises (
chai-as-promised).return expect(promise).to.eventually.equal(2)
Chai拥有丰富的生态系统。
- :用于API测试。
chai-http - :用于断言Promise(示例写法:
chai-as-promised)。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: reads better than
to.be.true.to.equal(true)
Don't:
- Don't mix Assert and Expect: Confuses the reader.
建议做法:
- 坚持使用单一风格:通常推荐Expect风格,它代码简洁且不会修改对象原型。
- 使用表意明确的链式调用:比
to.be.true的可读性更强。to.equal(true)
不建议做法:
- 不要混合使用Assert和Expect风格:这会让阅读者产生困惑。