QuickDevGuide

Home › Mocha JS Testing

Assertions with Chai — Mocha JS Testing

Chai is the assertion library most often paired with Mocha. It offers three styles: expect (most common), should and assert. Expectation Chai strict equality expect(x).to.equal(3) deep equality (objects/arrays) expect(obj).to.deep.equal({ a: 1 }) (or .eql) type expect(v).to.be.a("string"), .an("array") truthiness .to.be.true, .to.be.null, .to.be.undefined, .to.exist numbers .above(2), .within(1, 5), .closeTo(0.3, 1e-9) strings .include("abc"), .match(/regex/) collections .have.lengthOf(2), .include.members([1, 2]), .have.property("id", 7), .have.all.keys("a", "b") errors expect(() => fn()).to.throw(TypeError, /bad/) negation .not anywhere in the chain Install with npm i -D chai (Chai 5 is ESM-only: use import).

Key Takeaways