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.
See the Pen Testing with Mocha – Example 5.1 by Daniel Werner (@daniel-werner-the-decoder) on CodePen.
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 expect
and 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.
Expect
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.
See the Pen Testing with Mocha – Example 5.1 by Daniel Werner (@daniel-werner-the-decoder) on CodePen.
Should
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.
See the Pen Testing with Mocha – Example 5.2 by Daniel Werner (@daniel-werner-the-decoder) on CodePen.
Important to notice, that as opposed to expect should function should actually be called after requiring it.
const should = require('chai').should()
When using 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.
The post Testing with Mocha – 5. BDD style assertions with Chai appeared first on Daniel Werner.
Top comments (0)