Chai is a popular assertion library used in JavaScript testing, especially with testing frameworks like Mocha. It helps developers write readable and expressive tests by providing a variety of assertions to verify the behavior of their code.
Chai provides several types of assertions to test your code, mainly expect, should, and assert. These assertions help you check if your code works as expected
Example: expect(foo).to.equal('bar'); checks if foo is equal to bar.
Chai supports Behavior-Driven Development (BDD) style assertions with expect and should.
Example: expect(car).to.have.property('wheels'); checks if car has a property called wheels.
Chai also supports Test-Driven Development (TDD) style assertions with assert.
Example: assert.equal(a, b, 'a and b should be equal'); verifies that a is equal to b.
Chai is extendable with plugins, which provide additional assertions.
Example: chai-as-promised allows testing of promises easily.
Installing Chai is simple using npm.
Example: npm install chai --save-dev.
Chai integrates smoothly with Mocha, a popular JavaScript testing framework.
Example: const chai = require('chai'); const expect = chai.expect; describe('Array', function() { it('should start empty', function() { const arr = []; expect(arr).to.be.empty; }); });
Use .equal to check strict equality.
Example: expect(4 + 4).to.equal(8); checks if 4 + 4 equals 8.
.deep.equal checks equality of objects or arrays.
Example: expect({a: 1}).to.deep.equal({a: 1});.
.a or .an can check the type of a value.
Example: expect('hello').to.be.a('string'); checks if 'hello' is a string.
Use .ok to check if a value is truthy and .not.ok for falsy.
Example: expect(true).to.be.ok; and expect(false).to.not.be.ok;.
.lengthOf checks the length of strings or arrays.
Example: expect([1,2,3]).to.have.lengthOf(3);.
.property checks if an object has a certain property.
Example: expect(car).to.have.property('engine');.
.include checks if an array or string contains a value.
Example: expect([1, 2, 3]).to.include(2);.
.throw checks if a function throws an error.
Example: function badFunction() { throw new Error('Error!'); } expect(badFunction).to.throw('Error!');
Chai can handle asynchronous tests, often used with promises.
Example: return expect(Promise.resolve('done')).to.eventually.equal('done');