Back to Test Automation
2026-04-108 min read

list of available Chai assertions (Test Automation)

Learn list of available Chai assertions (Test Automation) step by step with clear examples and exercises.

Why This Matters

In this extensive guide, we will delve into the world of test automation using JavaScript, focusing on the popular assertion library, Chai. We'll explore various assertions available in Chai, learn how to write assertions for common use cases, and chain them together to create robust tests. By the end of this lesson, you'll have a solid understanding of Chai assertions and be able to apply them effectively in your test automation projects.

Why This Matters

Test automation is crucial for ensuring software quality and reducing manual testing efforts. Chai is a powerful assertion library that simplifies the process of writing tests by providing numerous assertion methods. By mastering Chai, you'll be able to write more efficient tests, catch bugs earlier in the development cycle, and ultimately deliver high-quality software faster.

Prerequisites

To follow along with this guide, you should have a basic understanding of:

  1. JavaScript programming language
  2. Node.js and npm (Node Package Manager) installed on your system
  3. Familiarity with test automation frameworks like Selenium, Cypress, or Playwright
  4. Understanding of the Mocha testing framework (Chai is used in combination with Mocha for writing tests)
  5. Basic understanding of HTTP requests and responses (for API testing examples)
  6. Familiarity with a simple web application or an API for testing purposes

Core Concept

Introduction to Chai

Chai is a BDD-style assertion library for JavaScript that makes it easy to write test cases and assertions. It provides a simple, readable syntax for testing your code and offers various assertion styles such as Expect (BDD), Should (BDD), and Assert (TDD). In this guide, we'll focus on using Chai with the Expect style.

Installing Chai

To install Chai in your project, run the following command in your terminal:

npm install chai

Basic Assertions

Chai provides several basic assertion methods that you can use to check whether a condition is true or false. Here are some examples:

const expect = require('chai').expect;

describe('Basic Assertions', function() {
it('should pass when value is equal', function() {
const value = 5;
expect(value).to.equal(5);
});

it('should fail when values are not equal', function() {
const value = 5;
expect(value).to.not.equal(6);
});

it('should pass when value is greater than', function() {
const value = 10;
expect(value).to.be.greaterThan(5);
});

it('should fail when value is less than', function() {
const value = 5;
expect(value).to.be.lessThan(10);
});

it('should pass when values are the same instance', function() {
const obj1 = {};
const obj2 = obj1;
expect(obj1).to.equal(obj2);
});

it('should fail when values are not the same instance', function() {
const obj1 = {};
const obj2 = {};
expect(obj1).not.to.equal(obj2);
});
});

Chaining Assertions

Chai allows you to chain multiple assertions together, which can help make your tests more readable and concise. Here's an example:

const expect = require('chai').expect;

describe('Chaining Assertions', function() {
it('should pass when chaining assertions', function() {
const value = { name: 'John Doe', age: 30 };

expect(value).to.be.an('object');
expect(value).to.have.all.keys('name', 'age');
expect(value.name).to.be.a('string');
expect(value.age).to.be.a('number');
expect(value.name).to.equal('John Doe');
expect(value.age).to.equal(30);
});
});

Deep Equality Assertions

Chai also provides deep equality assertions to compare complex objects or arrays for exact equality, including nested properties:

const expect = require('chai').expect;

describe('Deep Equality Assertions', function() {
it('should pass when objects are deeply equal', function() {
const obj1 = { name: 'John Doe', age: 30, hobbies: ['reading', 'gaming'] };
const obj2 = JSON.parse(JSON.stringify(obj1)); // Clone the object to compare deep equality

expect(obj1).to.deep.equal(obj2);
});

it('should pass when arrays are deeply equal', function() {
const arr1 = [1, 2, 3];
const arr2 = JSON.parse(JSON.stringify(arr1)); // Clone the array to compare deep equality

expect(arr1).to.deep.equal(arr2);
});
});

Worked Example

In this example, we'll create a simple test for an e-commerce application that checks the correctness of a user's login using Chai and Supertest:

const chai = require('chai');
const expect = chai.expect;
const { describe, it } = chai.run;
const request = require('supertest');
const app = require('../app'); // Assuming you have an Express app set up in the '../app' file

describe('Login Test', function() {
it('should log in a valid user', function(done) {
const user = { email: 'john@example.com', password: 'password123' };

request(app)
.post('/api/auth/login')
.send(user)
.end((err, res) => {
expect(res.status).to.equal(200);
expect(res.body.token).to.exist;
done();
});
});

it('should fail to log in an invalid user', function(done) {
const user = { email: 'invalid@example.com', password: 'password123' };

request(app)
.post('/api/auth/login')
.send(user)
.end((err, res) => {
expect(res.status).to.equal(401);
expect(res.body.message).to.equal('Invalid email or password');
done();
});
});

it('should fail to log in without providing an email', function(done) {
const user = { password: 'password123' };

request(app)
.post('/api/auth/login')
.send(user)
.end((err, res) => {
expect(res.status).to.equal(400);
expect(res.body.message).to.include('Email is required');
done();
});
});

it('should fail to log in without providing a password', function(done) {
const user = { email: 'john@example.com' };

request(app)
.post('/api/auth/login')
.send(user)
.end((err, res) => {
expect(res.status).to.equal(400);
expect(res.body.message).to.include('Password is required');
done();
});
});
});

Common Mistakes

  1. Forgetting to require Chai: Always remember to import Chai at the beginning of your test file using const chai = require('chai').
  2. Not defining expectations clearly: Make sure to define your expectations explicitly and use descriptive error messages when they fail.
  3. Using outdated versions of Chai or Mocha: Keep your dependencies up-to-date by running npm update periodically.
  4. Writing tests that are too slow or brittle: Avoid writing tests that take a long time to run, and make sure your tests are robust enough to handle changes in the application without breaking.
  5. Not testing edge cases: Ensure you test various scenarios, including edge cases, to catch potential issues early on.
  6. Not handling asynchronous tests properly: Use callbacks or Promises to handle asynchronous tests correctly.
  7. Ignoring error messages and stack traces: Pay close attention to the error messages and stack traces when your tests fail, as they can provide valuable insights into what went wrong.
  8. Writing tests that are too specific: Write generalized tests that cover multiple scenarios instead of writing individual tests for each specific case.
  9. Not refactoring tests after code changes: Update your tests to reflect any changes in the application's codebase, ensuring they continue to provide accurate results.
  10. Ignoring test coverage reports: Regularly review your test coverage reports to ensure that all critical parts of your application are covered by tests.

Practice Questions

  1. Write a test using Chai to check if a function returns the expected result for different input values (numbers and strings).
  2. Create a test that verifies an API endpoint's response status, data structure, and content (for example, checking if a list of users contains a specific user).
  3. Write a test to ensure that a user can successfully register with valid credentials using Chai and Supertest.
  4. Test a function that sorts an array of numbers in ascending order using Chai assertions.
  5. Write a test to check if a simple web application loads the correct HTML structure, CSS styles, and JavaScript files on page load.
  6. Create a test to verify that a specific API endpoint returns the expected response when provided with invalid input data (for example, an empty array or a non-numeric value).
  7. Write a test to check if a user can successfully reset their password using Chai and Supertest.
  8. Test a function that calculates the factorial of a number using Chai assertions.
  9. Create a test to verify that a specific API endpoint returns different responses based on various conditions (for example, returning an error message when a required parameter is missing).
  10. Write a test to check if a simple web application correctly handles form submissions and validates user input using Chai and Supertest.

FAQ

Q: What is the difference between BDD and TDD styles in Chai?

A: BDD (Behavior-Driven Development) style uses the should assertion style, while TDD (Test-Driven Development) style uses the assert assertion style.

Q: How do I install Chai and Mocha together?

A: You can install both Chai and Mocha using a single command: npm install --save chai chai-mocha chai-http mocha.

Q: Can I use Chai with other testing frameworks besides Mocha?

A: Yes, Chai is compatible with various testing frameworks like Jest and AVA as well.

Q: How do I handle asynchronous tests in Chai?

A: You can use callbacks or Promises to handle asynchronous tests in Chai. In the example provided earlier, we used the end callback from Supertest to handle the asynchronous API request.

Q: What is the purpose of deep equality assertions in Chai?

A: Deep equality assertions allow you to compare complex objects or arrays for exact equality, including nested properties, which can be useful when testing more complex data structures.

Q: How do I check if a function throws an error using Chai?

A: You can use the throw method from Chai to check if a function throws an expected error:

expect(function () {
// Your code here that should throw an error
}).to.throw('Expected error message');

Q: How do I test asynchronous functions using Chai and Mocha?

A: To test asynchronous functions, you can use the done callback provided by Mocha to signal when your test is complete. Here's an example:

describe('Asynchronous Function Test', function() {
it('should return expected result', function(done) {
const asyncFunction = require('./asyncFunction'); // Assuming you have an asynchronous function in the './asyncFunction' file

asyncFunction().then((result) => {
expect(result).to.equal('Expected result');
done();
}).catch((err) => {
console.error(err);
done();
});
});
});

In this example, the asyncFunction() is an asynchronous function that returns a Promise. The test uses the then method to handle the resolved value and the catch method to handle any errors that might occur during the execution of the asynchronous function. When the test completes successfully or encounters an error, it calls the done() callback to signal Mocha that the test is finished.

list of available Chai assertions (Test Automation) | Test Automation | XQA Learn