Chai Cheatsheet - Assertion Library
All essential Chai commands organized by use case, with 44+ entries you can copy and run directly. Find the right command fast when you need it.
Back to LanguagesExpect BDD 8
expect(value).to.equal(expected)相等断言(严格 ===)
expect(value).to.be.a("string")type断言
expect(array).to.include(item)package含断言
expect(value).to.be.true布尔断言
expect(value).to.not.be.null非空断言
expect(array).to.have.lengthOf(3)length断言
expect(value).to.existexists断言(非 null 且非 undefined)
expect(obj).to.have.property("key", "value")property及其值断言
Should BDD 5
value.should.equal(expected)相等断言
value.should.be.a("string")type断言
array.should.include(item)package含断言
value.should.be.true布尔断言
value.should.existexists断言
Assert TDD 7
assert.equal(actual, expected)相等断言
assert.notEqual(actual, expected)不等断言
assert.deepEqual(actual, expected)深度相等
assert.isTrue(value)为真断言
assert.isArray(value)array断言
assert.throws(fn)throwexception断言
assert.fail(actual, expected, "message")主动失败断言
Equality 6
expect(value).to.deep.equal(obj)深度compareobject/array
expect(value).to.eql(obj)deep.equal 别名
expect(value).to.not.equal(other)不相等断言
expect(obj).to.have.own.property("key")自有property断言(不含原型链)
expect(obj).to.have.nested.property("a.b.c")嵌套property断言
expect(arr).to.deep.equal([1, 2, 3])array深度compare
Type & Contain 6
expect(value).to.be.an("array")arraytype断言
expect(value).to.be.an.instanceof(Date)实例type断言
expect(str).to.match(/^foo/)正则Match断言
expect(str).to.have.string("bar")stringpackage含子串
expect(obj).to.include({ key: "value" })object部分package含
expect(arr).to.have.members([1, 2, 3])array成员完全相等
Exceptions 6
expect(fn).to.throw(Error)throwa given typeexception
expect(fn).to.throw("error message")throw含指定消息exception
expect(fn).to.throw(/message/)正则Matchexception消息
expect(fn).to.not.throw()不throwexception
assert.throws(fn, TypeError)TDD 抛错断言
assert.doesNotThrow(fn)TDD 不抛错断言
Number, Boolean & Plugins 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 state断言(需 chai-http)
💡 Tips
- expect 和 should 是 BDD 风格,assert 是 TDD 风格。
- should 需要对objectcall .should,可能对 null/undefined 报错。
- 深度compare用 .deep.equal,浅compare用 .equal。
- chai-as-promised 插件supports Promise 断言,chai-http supports HTTP request断言。
- 链式method如 to、be、have 仅提高可读性,无实际功能。
Official References
Commands are compiled from the official docs below. Click to verify the latest usage.
Maintained by LaoHand
Publicly updated on Jul 21, 2026, continuously proofread against official docs.
Found an error? Report it
Wrong command or description? Open an issue to help us fix it.
Found an error? Report it