Errors, Collections & Plugins
Asserting Thrown Errors
// pass the function reference — do NOT call it inside expect()
expect(() => myFunction()).to.throw(Error);
expect(() => validate(input)).to.throw(ValidationError, 'required field missing');
// calling it directly is a common mistake — the exception fires
// before expect() can wrap and catch it, crashing the test itself
// expect(myFunction()).to.throw(); // WRONGArrays, Objects & Keys
expect([1, 2, 3]).to.include(2);
expect([1, 2, 3]).to.have.lengthOf(3);
expect(obj).to.have.property('name', 'Ada');
expect(obj).to.have.keys('id', 'name'); // exact key set
expect(obj).to.include.keys('id'); // present among possibly others
expect(obj).to.be.an.instanceof(User);Nullish Checks
expect(value).to.be.null; // strictly === null
expect(value).to.not.exist; // null OR undefined
expect(value).to.exist; // neither null nor undefinedPlugins
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const sinonChai = require('sinon-chai');
chai.use(chaiAsPromised);
chai.use(sinonChai);
await expect(fetchUser(1)).to.eventually.have.property('name', 'Ada');
expect(mySpy).to.have.been.calledOnce;isTrue vs. ok (assert style)
assert.isTrue(value) checks the value is strictly true; assert.ok(value) only checks truthiness (passes for 1, 'hello', {}). Prefer isTrue() when you specifically expect a boolean, to catch a bug returning e.g. 1 instead of true.
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free