Chai
01 / 02

expect/should Style & Core Assertions

expect/should Style & Core Assertions

Three Styles

Chai supports assert (TDD-style function calls), expect, and should (both BDD-style chainable syntax). Mocha ships with no assertion library of its own, which is why Chai is so commonly paired with it — Jest, by contrast, bundles its own expect.

const { expect, assert } = require('chai');

// BDD style — reads like a sentence
expect(user.age).to.be.above(18);
expect(user.name).to.equal('Ada');

// TDD style
assert.isAbove(user.age, 18);
assert.equal(user.name, 'Ada');

equal vs. eql (Deep Equality)

const a = { id: 1 };
const b = { id: 1 };

expect(a).to.equal(a);   // passes — same reference
expect(a).to.equal(b);   // FAILS — different object instances
expect(a).to.eql(b);     // passes — deep/structural comparison
expect(a).to.deep.equal(b); // same as .eql()

Chainable Language Words

Words like .to, .be, .been, .is, .that, .and, .have, .with are no-ops purely for readability — expect(x).to.be.an('array') and expect(x).an('array') do the exact same thing.

Negation, Type & Numeric Checks

expect(value).to.not.equal(5);
expect(value).to.be.an('array');
expect(value).to.be.a('string');
expect(number).to.be.above(5);     // > 5
expect(number).to.be.at.least(5);  // >= 5
expect(number).to.be.below(10);    // < 10
expect(number).to.be.at.most(10);  // <= 10

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free