How to use chai assertion library
In this article, you will learn about how to use the Chai assertion library.
Assertion libraries are tools to verify that things are correct. Basically, It helps you to test your code and reduce your time by preventing writing thousands of if statements. Chai is an assertion library.
More specifically, Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.
BDD stands for Behavior-Driven Development and TDD stands for Test-Driven Development. Chai lets you perform 3 different assertion styles. These are :
- expect
- should and
- assert.
Here, expect and should use in the BDD style. To construct assertions, both use the same chainable language
Moving On With expect: In Chai, the expect styles will allow you to chain together natural language assertions. Follow the code below:
const expect = require('chai').expect
, foo = 'bar'
, cars = { brand: [ 'BMW', 'Audi', 'Bentley' ] };
expect(foo).to.be.a('string');
expect(foo).to.equal('bar');
expect(foo).to.have.lengthOf(3);
expect(cars).to.have.property('brand').with.lengthOf(3);
Moving On With should:The should style also implement for the same chainable assertions as the expect interface. The only difference is that it extends each object with a should property to start your chain. For example:
const should = require('chai').should() //actually call the function
, foo = 'bar'
, cars = { brand: [ 'BMW', 'Audi', 'Bentley' ] };
foo.should.be.a('string');
foo.should.equal('bar');
foo.should.have.lengthOf(3);
cars.should.have.property('brand').with.lengthOf(3);
Note: You should be aware of browser compatibility. Because this style has some issues when used with Internet Explorer.
Moving On With assert: The assert style provides the classic assert-dot notation, similar to that packaged with node.js. This assert module provides you with several additional tests and browser compatibility also. Example of assert :
var assert = require('chai').assert
, foo = 'bar'
, cars = { brand: [ 'BMW', 'Audi', 'Bentley' ] };
assert.typeOf(foo, 'string'); // without optional message
assert.typeOf(foo, 'string', 'foo is a string'); // with optional message
assert.equal(foo, 'bar', 'foo equal `bar`');
assert.lengthOf(foo, 3, 'foo`s value has a length of 3');
assert.lengthOf(cars.brand, 3, 'cars has 3 types of brand');
Here, In all cases, the assert style allows you a very handy option and that is you can include an optional message as the last parameter in the assert statement. These will be included in the error messages should your assertion not pass.
This is an overview of the chai assertion library and you can learn from it.