Chai 断言库速查表

Chai 是 JavaScript BDD/TDD 断言库,支持 should、expect、assert 三种风格。

编程语言·共 22 条命令·最后更新 2026-07-19
返回 编程语言

Expect 风格(BDD) 6

expect(value).to.equal(expected)
相等断言
expect(value).to.be.a("string")
类型断言
expect(array).to.include(item)
包含断言
expect(value).to.be.true
布尔断言
expect(value).to.not.be.null
非空断言
expect(array).to.have.lengthOf(3)
长度断言

Should 风格(BDD) 4

value.should.equal(expected)
相等断言
value.should.be.a("string")
类型断言
array.should.include(item)
包含断言
value.should.be.true
布尔断言

Assert 风格(TDD) 6

assert.equal(actual, expected)
相等断言
assert.notEqual(actual, expected)
不等断言
assert.deepEqual(actual, expected)
深度相等
assert.isTrue(value)
为真断言
assert.isArray(value)
数组断言
assert.throws(fn)
抛出异常断言

常用链式方法 4

expect(value).to.be
语言链(无功能)
expect(value).to.not
取反断言
expect(value).to.deep.equal(obj)
深度比较
expect(value).to.have.property("key")
属性断言

异步断言 2

expect(promise).to.eventually.equal("resolved")
Promise 断言(需 chai-as-promised)
expect(fn).to.throw(Error)
同步异常断言

💡 提示

  • expect 和 should 是 BDD 风格,assert 是 TDD 风格。
  • should 需要对对象调用 .should,可能对 null/undefined 报错。
  • 深度比较用 .deep.equal,浅比较用 .equal。
  • chai-as-promised 插件支持 Promise 断言。
  • 链式方法如 to、be、have 仅提高可读性,无实际功能。