Chai is a BDD / TDD assertion library for Node.js and the browser that can be delightfully paired with any JavaScript testing framework (such as Mocha or Jest).
BDD Style (expect)
const { expect } = require('chai');
Equality & Types
expect(val).to.equal(expected); // Strict equality (===)
expect(val).to.eql(expected); // Deep equality
expect(val).to.deep.equal(expected); // Same as .eql
expect(val).to.be.a('string');
expect(val).to.be.an('array');
expect(val).to.be.an.instanceOf(User);
Truthiness & Presence
expect(val).to.be.ok; // Truthy
expect(val).to.be.true;
expect(val).to.be.false;
expect(val).to.exist; // Not null and not undefined
expect(val).to.be.null;
expect(val).to.be.undefined;
expect(val).to.be.empty; // Array, string, or object with 0 length/keys
Numerical Comparisons
expect(score).to.be.above(5); // Greater than (gt)
expect(score).to.be.at.least(5); // Greater than or equal (gte)
expect(score).to.be.below(10); // Less than (lt)
expect(score).to.be.at.most(10); // Less than or equal (lte)
expect(score).to.be.within(5, 10); // Inclusive range
expect(pi).to.be.closeTo(3.14, 0.01); // Float tolerance
Objects & Collections
expect(array).to.include(item);
expect(array).to.have.members([1, 2, 3]);
expect(array).to.have.lengthOf(3);
expect(obj).to.have.property('name');
expect(obj).to.have.property('name', 'Alice');
expect(obj).to.have.nested.property('address.city', 'London');
expect(obj).to.have.all.keys('id', 'name');
Function Throws
expect(() => badFunction()).to.throw();
expect(() => badFunction()).to.throw(TypeError);
expect(() => badFunction()).to.throw(/invalid argument/);
expect(() => goodFunction()).to.not.throw();
TDD Style (assert)
const { assert } = require('chai');
assert.ok(val, 'value is truthy');
assert.equal(actual, expected, 'compares with ==');
assert.strictEqual(actual, expected, 'compares with ===');
assert.deepEqual(actual, expected, 'deep equality');
assert.isTrue(val);
assert.isFalse(val);
assert.isNull(val);
assert.isNotNull(val);
assert.isUndefined(val);
assert.isDefined(val);
assert.typeOf(val, 'string');
assert.instanceOf(val, Model);
assert.lengthOf(val, 3);
assert.include(list, item);
assert.match(str, /regex/);
assert.throws(() => { ... }, /error regex/);
Chai with jQuery (chai-jquery)
chai.use(require('chai-jquery'));
// DOM state checks
expect($elem).to.be.visible;
expect($elem).to.be.hidden;
expect($elem).to.be.enabled;
expect($elem).to.be.disabled;
expect($elem).to.be.checked;
// CSS & attributes
expect($elem).to.have.class('active');
expect($elem).to.have.id('submit-btn');
expect($elem).to.have.attr('disabled');
expect($elem).to.have.css('display', 'block');
expect($elem).to.have.text('Hello World');