Table of contents
1.
Introduction
2.
Getting Started
2.1.
Program
2.2.
Test Program
2.3.
Output
3.
Assertions In mocha
4.
Example of assert.strictEqual
5.
Example of Async Test with Callback
5.1.
Program
5.2.
Test Program
5.3.
Output
6.
Example of Async Test with Promises
6.1.
Program
6.2.
Test Program
6.3.
Output
7.
FAQs
8.
Key Takeaways
Last Updated: Mar 27, 2024

Mocha Assertions

Author Aman Thakur
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Software testing is an essential aspect of the development process. It's typical practice for programmers to run code that tests their application as they make changes to ensure it's performing as expected. This procedure may even be automated with the correct test configuration, saving a lot of time. Running tests after developing new code regularly guarantees that new modifications do not damage current functionality.This instils trust in the developer's code base, especially when it's put to production and users may interact with it.

A test framework structures the method we build test cases. Mocha is a popular JavaScript test framework that helps us structure and run our test cases. On the other hand, Mocha does not check the behaviour of our code. Assertions are the way of checking the truthness of a given piece of code and whether it properly functions as it is expected to do so. The assert module in Node.js may be used to compare data in a test.

Getting Started

If you are looking out for setup just check out an article on getting started with Mocha, it covers the basic description regarding guidelines for initial setup. The article will stress upon the practical example of the implementation of assertion libraries in mocha. So enough discussion. Lets get our hands dirty by coding the things up given below.

Program

// create lib/first.js
function first(array){
  if (array && array.length){
      return array[0];
  }
};

module.exports = first;
You can also try this code with Online Javascript Compiler
Run Code

Test Program

// create test/first-test.js
const assert = require('assert');
const first = require('../lib/first');

describe('first test', () => {
  it('returns first element of the array', () => {
      var result = first([1, 2, 3]);

      assert.equal(result, 1, 'first element of [1, 2, 3] is 1');
  });
});
You can also try this code with Online Javascript Compiler
Run Code

Output

Assertions In mocha

  1. assert.ok is the simplest assertion, which verifies the value's authenticity. you only used this when you don't care about the exact value and simply care that it isn't false.
  2. assert.equal performs a weak equality check. assert. strictEqual, on the other hand, is presumably safer because it does a strict equality check.
  3. assert.deepEqual is quite beneficial. It tests in a recursive manner, so you may use it to validate entire JSON trees, for example. It's worth noting that it employs sloppy equality checking.
  4. assert.throws are used to check for errors raised by functions. It executes the provided code and anticipates an exception. You may even specify which exception is thrown by giving a second option.
     

And there is also the inverse of these which are possible notEqual, notStrictEqual, notDeepEqual, doesNotThrow. They do exactly what you'd expect them to do!

Example of assert.strictEqual

it("returns undefined if array is empty", () => {
  var result = first([]);
  assert.strictEqual(result, undefined, "maybeFirst([]) is undefined");
});
You can also try this code with Online Javascript Compiler
Run Code

Example of Async Test with Callback

Program

// create delayedMap.js
function delayedMap(array, transform, callback) {
setTimeout(function () {
  callback(array.map(transform));
}, 100);
}

module.exports = delayedMap;
You can also try this code with Online Javascript Compiler
Run Code

Test Program

// create delayedMapTest.js
const assert = require("assert");
const delayedMap = require("../lib/delayed-map");

describe("Delayed Map Test", () => {
it("eventually returns the results", function () {
  var input = [1, 2, 3];
  var transform = function (x) {
    return x * 2;
  };

  delayedMap(input, transform, function (result) {
    assert.deepEqual(result, [2, 4, 6]);
  });
});
});
You can also try this code with Online Javascript Compiler
Run Code

Output

Example of Async Test with Promises

Program

// create promise.js
function promiseMap(array, transform) {
  return new Promise( function(resolve, reject) {
      setTimeout(function() {
          resolve(array.map(transform));
      }, 100);
  });
}

module.exports = promiseMap;
You can also try this code with Online Javascript Compiler
Run Code

Test Program

// create promiseTest.js
const assert = require("assert");
const promiseMap = require("../lib/promises");

describe("second test", function () {
it("eventually returns the results", function () {
  let input = [1, 2, 3];
  let transform = function (x) {
    return x * 2;
  };

  return promiseMap(input, transform).then(function (result) {
    assert.deepEqual(result, [2, 4, 6]);
  });
});

it("eventually returns the results", function (done) {
  var input = [1, 2, 3];
  var transform = function (x) {
    return x * 2;
  };

  return promiseMap(input, transform).then(function (result) {
    assert.deepEqual(result, [2, 4, 6]);
  });
});
});
You can also try this code with Online Javascript Compiler
Run Code

Output

FAQs

  1. Does Mocha run tests in parallel?
    Individual tests are not executed in parallel by Mocha. That is, if you provide Mocha a solitary, lonely test file, it will create a single worker process, which will run the file. You'll be penalised for using parallel mode if you just have one test file.
     
  2. Is Mocha an assertion library?
    Mocha is a JavaScript test framework for Node.js applications that supports browser compatibility, asynchronous testing, reporting on test coverage, and the use of any assertion library.
     
  3. How do you test your promises with Mocha?
    If a function produces a promise that you want to assert on the function's outcome, It return the promise in your block for it to work with Mocha. Then you may assert on the promise's outcome in the chain.
     
  4. What is Mocha chai testing?
    In a nutshell, Mocha is a Node-based JavaScript test framework that tests coverage reports. Chai is a TDD assertion library for NodeJS and the browser, and it's the next testing tool we'll discuss.Any Javascript testing framework may simply be used with Chai.

Key Takeaways

If you read till here you really enjoyed the article and learned a lot here are few words which summarises the article, A test framework organises the way we create test cases.Mocha is a well-known JavaScript test framework that aids in the organisation and execution of our test cases. On the other hand, Mocha does not examine our code's behaviour. To compare data in a test, use the assert module in Node.js.

You might be interested in articles such as Fundamentals of Software TestingRunning Mocha in Browser, or Mocha Introduction and Feature. Hence never stop your quest for learning. Do upvote our blog to help other ninjas grow. We wish you Good Luck! Keep coding and keep reading Ninja.
Happy Learning!

Live masterclass