Chai 断言库速查表 - Chai.js 测试断言 expect/should/assert 大全

这张速查给用 Mocha、Jest 集成或纯 Node 写 JavaScript 测试的开发者。Chai 提供了 expect、should、assert 三种可互换的风格,这张表会把同一种检查用不同写法各展示一遍。内容覆盖相等与对象/数组的深度比较、类型与包含检查、抛错断言、数值区间,以及依赖插件的助手方法,比如 eventually(chai-as-promised)和 HTTP 状态码(chai-http)。读完你应能对值、集合、抛错和 Promise 写出清晰易读的断言,并明白什么时候该用 deep.equal 而不是 equal。

编程语言·共 44 条命令·最后更新 2026-07-21

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)
断言该值严格等于 true
assert.isArray(value)
断言该值是数组类型
assert.throws(fn)
断言执行 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)

提示

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

官方参考来源

下方为命令对应的官方权威文档,供你核对最新用法与深入查阅。

由 巧匠 维护

公开更新于 2026年7月21日,内容持续校对官方文档。

联系我们

命令或描述有误?提交反馈、商务合作或产品建议都可发送邮件给我们。

联系我们