Table of contents
1.
Introduction
2.
Setup
3.
Approaches to Asynchronous Testing
3.1.
Async/await
3.1.1.
Program
3.2.
Promise chaining
3.2.1.
Program
3.3.
Callbacks function
4.
Implementation
4.1.
Test Program
4.2.
Output
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Testing Asynchronous Code

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

Introduction

The article teaches you how to handle asynchronous code and promises successfully when testing with Mocha. We will go through the best (and simplest) approach to test async code in Mocha, and let deep dive to better understand how async handling works in Mocha through code.

The Mocha test framework well supports Async tests. In general, there are three approaches to structure async tests in Mocha:

  1. async/await
  2. promise chaining
  3. callbacks

Let’s get started with asynchronous code testing with Mocha.

Setup

First of all create a directory named it as you wish, inside it run the command initialise it with package.json and then install Mocha as dev dependency and create a file index.js

The file structure:

The package.json file:

{
 "name": "aync-Mocha-test",
 "version": "1.0.0",
 "main": "index.js",
 "author": "aman-thakur",
 "license": "MIT",
 "dependencies": {
   "axios": "^0.26.0"
 },
 "scripts": {
   "test": "Mocha index.js"
 },
 "devDependencies": {
   "Mocha": "^9.2.1"
 }
}

Approaches to Asynchronous Testing

Async/await

When you convert to async/await format, you get the same advantages as the promise, which we will discuss later on in the same article,  returning an example, but with significantly easier-to-read formatting. No plugins or setup are required to use async functions in Mocha. You may use it() to supply an async function, and Mocha will handle any issues.

Program

describe("Implementation of async function",  () => {
 it("works great", async () => {
   const result = await get("http://httpbin.org/get?answer=42");
   assert.equal(result.data.args.answer, 42);
 });
});
You can also try this code with Online Javascript Compiler
Run Code

Promise chaining

Because Mocha chains its own .then after the.then containing the assertions, the returning method works. Mocha guarantees that the test suite is always marked as green by adding an additional .then.  async functions have been supported by Mocha since 2014. Although async functions were only introduced in 2017, they return promises, which Mocha has supported since before they were officially introduced into JavaScript.

In other words, if your it() method returns a promise or promise, Mocha will take care of it.

Program

describe("Implementation of promise function",  () => {
 it("works great",  () => {
   return get("http://httpbin.org/get?answer=42").then((result) =>
     assert.equal(result.data.args.answer, 42)
   );
 });
});
You can also try this code with Online Javascript Compiler
Run Code

Callbacks function

When utilising the request and util libraries isn't an option,so you need to wrap your callback function in promises, whether it be  due to a legacy environment/code base or making requests from the client-side browser. Lets see an example of it given below

describe("Implementation of callbacks using done", () => {
 it("works great", function (done) {
   get("http://httpbin.org/get?answer=42")
     .then((result) => {
       assert.equal(result.data.args.answer, 42);
       done();
     })
     .catch((error) => done(error));
 });
});
You can also try this code with Online Javascript Compiler
Run Code

Implementation

Test Program

const axios = require("axios");
const assert = require("assert");

function get(url, cb) {
 return axios.get(url);
}

describe("Implementation of async function",  () => {
 it("works great", async () => {
   const result = await get("http://httpbin.org/get?answer=42");
   assert.equal(result.data.args.answer, 42);
 });
});

describe("Implementation of promise function",  () => {
 it("works great",  () => {
   return get("http://httpbin.org/get?answer=42").then((result) =>
     assert.equal(result.data.args.answer, 42)
   );
 });
});

describe("Implementation of callbacks using done", () => {
 it("works great", function (done) {
   get("http://httpbin.org/get?answer=42")
     .then((result) => {
       assert.equal(result.data.args.answer, 42);
       done();
     })
     .catch((error) => done(error));
 });
});
You can also try this code with Online Javascript Compiler
Run Code

Output

FAQs

  1. What is asynchronous testing?
    Code that runs asynchronously is prevalent in JavaScript. When testing asynchronous code, Jest needs to know when the code it's testing is finished before go to the next test.
     
  2. What is a callback in protractor?
    As the name implies, a callback is a function that is called after another function has completed its execution. Functions are objects in JavaScript, as we all know. As a result, functions can accept functions as arguments and return them to other functions.
     
  3. What is the difference between async ()' and fakeAsync ()'?
    They may be used interchangeably in virtually all circumstances, however the fakeAsync()/tick() combination is recommended unless you need to make an XHR call, in which case you MUST use the async()/whenStable() combination, as fakeAsync() does not allow XHR calls.They may be used interchangeably for the most part.
     
  4. What is done () in Jasmine?
    If the function supplied to Jasmine takes an argument (traditionally known as done), Jasmine will pass a function that will be called when the asynchronous operation is finished.

Key Takeaways

If you reached till here that means you really enjoyed reading this article and might it be helpful to you. Here are some important insights from this article that cover unit testing with Mocha and handle asynchronous code and promises correctly.

You might be interested in articles such as Fundamentals of Software Testing. Hence never stop your quest for learning. We wish you Good Luck! Keep coding and keep reading Ninja.

Happy Learning! 

Live masterclass