QA Notes | Mocha Chai

Learn the basics of Chai, a BDD/TDD assertion library for node.

Posted by PeCoBe on 2022-10-16 ·

Chai is a assertions library, that can be paired with any testing framework based in JavaScript.

In this post we are going to review the following topics

  • What is Chai, how to install?
  • Assertion Styles
  • Differences
  • Adding Chai assertions to projects
  • Centralizing assertions

Assertions

What is an assertion? Is an expression which encapsulates some testable logic specified about a target under test. - Is always True OR False.

Chai is clasified into two:

  • BDD (expect, should)
  • TDD (assert)

BDD - Behavior-driven development language, is an expressive language in a readable style. TDD - Test-driven development, more classical feel.

Pre-requisites for Mocha

  1. NodeJS
  2. Node Package Manager NPM
mkdir /path/to/newfolder
node -v #verify node version
npm -v #verify npm version
npm install chai -save-dev #install chai

Import Chai to project adding the following code

const chai = require('chai');

And run from the terminal

npm test/myfile.js

How to use Expect, Should and Assert

See code.

Expect vs Should vs Assert

  • Expect supports Node.js and all modern browsers.
  • Should doesn't support Internet Explorer.
  • Should extends Object.Prototype

Manage undefined with should

// normal scenario
error.should.not.exist();
// given that error is undefined
should.not.exist(error);

Configurations

chai.config.showDiff = false; // turn off reported diff display
chai.config.truncateThreshol = 0; // disable truncating
chai.config.includeStack = true; // turn on stack trace

Adding Chai to your project

  1. Install Chai using npm install chai -save-dev

  2. Add Chai variables

const chai = require('chai');
const assert = chai.assert;
const expect = chai.expect;
const should = chai.should();
  1. Use chai assertions

Thats the end of the introduction. You should be able to start working from here. Next step will be combining it with an automation framework, like Selenium.

  • What is Chai, how to install?
  • Assertion Styles
  • Differences
  • Adding Chai assertions to projects
  • Centralizing assertions