Chai Cheatsheet - Assertion Library

Chai.js 测试断言必备 API 都在这里了,从 expect 风格到 assert 风格,按类别分类整理,写代码时直接复制。

Languages·44 commands·Last updated 2026-07-21
Back to Languages

Expect 风格(BDD) 8

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)
长度断言
expect(value).to.exist
存在断言(非 null 且非 undefined)
expect(obj).to.have.property("key", "value")
属性及其值断言

Should 风格(BDD) 5

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

Assert 风格(TDD) 7

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

相等与深度比较 6

expect(value).to.deep.equal(obj)
深度比较对象/数组
expect(value).to.eql(obj)
deep.equal 别名
expect(value).to.not.equal(other)
不相等断言
expect(obj).to.have.own.property("key")
自有属性断言(不含原型链)
expect(obj).to.have.nested.property("a.b.c")
嵌套属性断言
expect(arr).to.deep.equal([1, 2, 3])
数组深度比较

类型与包含断言 6

expect(value).to.be.an("array")
数组类型断言
expect(value).to.be.an.instanceof(Date)
实例类型断言
expect(str).to.match(/^foo/)
正则匹配断言
expect(str).to.have.string("bar")
字符串包含子串
expect(obj).to.include({ key: "value" })
对象部分包含
expect(arr).to.have.members([1, 2, 3])
数组成员完全相等

异常与抛错 6

expect(fn).to.throw(Error)
抛出指定类型异常
expect(fn).to.throw("error message")
抛出含指定消息异常
expect(fn).to.throw(/message/)
正则匹配异常消息
expect(fn).to.not.throw()
不抛出异常
assert.throws(fn, TypeError)
TDD 抛错断言
assert.doesNotThrow(fn)
TDD 不抛错断言

数字、布尔与插件 6

expect(num).to.be.above(5)
大于断言
expect(num).to.be.at.least(5)
大于等于断言
expect(num).to.be.below(10)
小于断言
expect(num).to.be.within(1, 10)
区间断言(含边界)
expect(promise).to.eventually.equal("resolved")
Promise 断言(需 chai-as-promised)
expect(res).to.have.status(200)
HTTP 状态断言(需 chai-http)

💡 Tips

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