Getting started with Chai

Chai itself has a few different flavors of API styles that can be used when writing tests. The BDD API, which is what we will use for the tests we write, uses expect and should. There's also the assert API, which is more of a TDD style. The benefit of using the BDD style with expect/should is that you can chain the assertion methods to improve readability of the tests.

You can learn more about BDD and TDD by accessing the following Wikipedia page:
http://en.wikipedia.org/wiki/Behavior-driven_development

Using the BDD assertion API with Chai.js provides a number of methods at our disposal, such as to, be, is, and many more. They have no testing capability, but instead they improve the assertion readability. All the getters are listed at http://chaijs.com/api/bdd/.

All of these getters will follow an expect() statement and can be coupled with not, in case we want to flip the assertion negatively.

The preceding getters are combined with the chai assertion methods, such as ok, equal, within, and so on, to determine a test's outcome. All those methods are listed at http://chaijs.com/api/assert/.

Let's start constructing simple assertions.The chai provides three different assertion styles: expect, should, and assert. Consider the following simple illustration:

const chai = require('chai'); 
const expect = chai.expect;
const should = chai.should();
const assert = chai.assert;
const animals = { pets: [ 'dog', 'cat', 'mouse' ] };
const foo = 'bar';

expect(foo).to.be.a('string').and.equal('bar');
expect(animals).to.have.property('pets').with.length(4);
animals.should.have.property('pets').with.length(4);
assert.equal(foo, 'bar', 'Foo equal bar');

As you can see, the expect/should function is based on self-descriptive language chains. Both differ in their way of declaration--the expect function provides a starting point for a chain, whereas the should interface extends an Object.prototype.

The assert interface provides simple but powerful TDD style assertions. Apart from the preceding example that yields a deep equality assertion, exception testing, and instance are also available. For more in-depth learning, refer to the Chai documentation at http://chaijs.com/api.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.72.245