Chai is a TDD and BDD library, and comes with several flavors for assertions: should, expect and assert. In the following lessons we will take a look at both styles and see how to use them in practice.
Installation and first example
First we need to install chai using a package manager, for example npm:
npm install chai
When it is done, let’s take a look at our first example with chai.
As we see in this example we are using expect instead of assert, let’s see some more details about the different assertion styles, which can be used in Chai.
The BDD style assertions are
should. Both use the chainable getters to create nice and readable assertions.
The basic difference between expect and should is how they create the chain of expectations.
Using expect you have to wrap the asserted value with and
expect() function call, and create the chainable assertion afterwards. Let’s see an example.
Should provides the same chainable interface as expect, but should extends all the objects with a should property. This should property can be used to create the assert chain.
Let’s see the previous example rewritten with should.
Important to notice, that as opposed to expect should function should actually be called after requiring it.
const should = require('chai').should()
should with ES2015 style imports, the function call should go on separate line, like:
import chai from 'chai'; chai.should();
As opposed to equal, which only needs to be required/imported.
const expect = require('chai').expect;
For more information about should and expect style assertions check the Chai documentation.
Check out all posts in the series Testing with Mocha.