JavaScript

How to Test Asynchronous Code With Mocha.js

Asynchronous code is everywhere in Node.js applications. Whether you are calling an API, reading a file, querying a database, or using a timer, the result…

D
DevByteTechnical Author
Published
17 min read3 views
Mocha async testing in Node.js

Asynchronous programming is an essential part of modern JavaScript development. Whether you are working with database queries, HTTP requests, file operations, or external APIs, your application frequently needs to perform tasks that do not complete immediately.

Testing these operations can be challenging because a test must wait for the asynchronous task to finish before determining whether it passed or failed.

This is where Mocha async testing becomes useful.

Mocha is a popular JavaScript testing framework that supports asynchronous tests using callbacks, Promises, and async/await. It allows developers to verify that asynchronous functions behave correctly, handle errors properly, and return the expected results.

In this guide, you will learn how asynchronous testing works in Mocha, how to test Promises and async/await, how to handle errors, and how to avoid common testing mistakes in Node.js applications.

What Is Mocha?

Mocha is an open-source JavaScript testing framework commonly used to test Node.js applications and JavaScript code.

It provides a flexible structure for organizing and running tests. Developers can use Mocha with assertion libraries such as Node.js's built-in assert module or Chai.

Mocha supports:

  • Synchronous tests

  • Callback-based asynchronous tests

  • Promise-based tests

  • Tests using async/await

  • Hooks such as before(), after(), beforeEach(), and afterEach()

  • Test suites organized with describe() and individual tests written with it()

Mocha does not require a particular assertion library, so developers can choose the tools that fit their projects.

For example, a basic Mocha test looks like this:

const assert = require('node:assert/strict');

describe('Math operations', function () {
  it('should add two numbers', function () {
    const result = 2 + 3;

    assert.equal(result, 5);
  });
});

The describe() function groups related tests, while it() defines an individual test case.

This example is synchronous because the calculation completes immediately.

However, real-world applications frequently involve asynchronous operations that need a different approach.

What Is Asynchronous Testing in Mocha?

Asynchronous testing verifies code that does not produce its final result immediately.

Examples include:

  • Fetching data from an API

  • Reading a file

  • Querying a database

  • Authenticating a user

  • Sending an email

  • Processing a background task

  • Waiting for a timer

Consider a function that retrieves user information after a short delay:

function getUser() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        id: 1,
        name: 'Alex'
      });
    }, 1000);
  });
}

The function returns a Promise that resolves after one second.

If a test calls getUser() and immediately checks the result without waiting, the assertion will run before the data is available.

Mocha solves this problem by allowing asynchronous tests to signal when their work has completed.

Depending on how the function is implemented, you can use:

  1. A callback parameter named done

  2. A returned Promise

  3. The async/await syntax

Important: A Mocha test should use one completion mechanism at a time. Do not combine the done callback with a returned Promise or an async test function.

Setting Up Mocha in a Node.js Project

Before writing asynchronous tests, create a Node.js project and install Mocha.

Step 1: Initialize a Node.js Project

Open your terminal and run:

mkdir mocha-async-demo
cd mocha-async-demo
npm init -y

This creates a new project directory and generates a package.json file.

Step 2: Install Mocha

Install Mocha as a development dependency:

npm install --save-dev mocha

Step 3: Configure the Test Script

Open package.json and add a test script:

{
  "scripts": {
    "test": "mocha"
  }
}

Keep the other fields already generated by npm.

Now you can run your tests with:

npm test

Mocha looks for test files in the test directory by default.

Step 4: Create the Test Directory

Create a directory named test and add a file called async.test.js.

Your project structure should look similar to this:

mocha-async-demo/
├── node_modules/
├── test/
│   └── async.test.js
├── package.json
└── package-lock.json

You are now ready to write your first asynchronous test.

Method 1: Testing Asynchronous Code Using Callbacks

Callbacks are functions passed to other functions so they can be executed after an operation completes.

In Mocha, the done callback tells the framework when an asynchronous test has finished.

Consider this function:

function getMessage(callback) {
  setTimeout(() => {
    callback(null, 'Hello from Node.js!');
  }, 500);
}

module.exports = { getMessage };

The function waits for 500 milliseconds and then invokes the callback with a message.

Create a file named message.js and add the code above.

Now write the following test in test/async.test.js:

const assert = require('node:assert/strict');
const { getMessage } = require('../message');

describe('getMessage()', function () {
  it('should return the expected message', function (done) {
    getMessage((error, message) => {
      if (error) {
        return done(error);
      }

      try {
        assert.equal(message, 'Hello from Node.js!');
        done();
      } catch (error) {
        done(error);
      }
    });
  });
});

Run the test:

npm test

How Does This Test Work?

Let's break it down.

1. Mocha detects the done parameter.

it('should return the expected message', function (done) {

Mocha recognizes that the test expects a callback.

2. The asynchronous function is executed.

getMessage((error, message) => {

The test waits for getMessage() to invoke its callback.

3. Errors are handled.

if (error) {
  return done(error);
}

Passing an error to done() tells Mocha that the test failed.

4. The assertion verifies the result.

assert.equal(message, 'Hello from Node.js!');

If the message is incorrect, the assertion throws an error.

5. The test completes.

done();

Calling done() without an error signals that the asynchronous test has finished successfully.

Why Is Error Handling Important Here?

Suppose the assertion fails inside the callback.

Without the try/catch block, the thrown assertion error may escape the callback and not be reported as a normal failure of the done-based test.

Wrapping the assertion and passing the error to done(error) ensures Mocha receives the failure.

For callback-based tests, always make sure every successful execution calls done() and every error path reports the error.

Method 2: Testing Promises in Mocha

Promises are a common way to handle asynchronous operations in JavaScript.

A Promise represents a value that may become available in the future or an operation that may fail.

Mocha supports Promises directly. If a test returns a Promise, Mocha waits for that Promise to settle.

Let's create a function that returns a Promise.

Example: Promise-Based Function

Create userService.js:

function getUser() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        id: 1,
        name: 'Alex'
      });
    }, 500);
  });
}

module.exports = { getUser };

Now create a test in test/async.test.js:

const assert = require('node:assert/strict');
const { getUser } = require('../userService');

describe('getUser()', function () {
  it('should return the correct user', function () {
    return getUser().then((user) => {
      assert.equal(user.id, 1);
      assert.equal(user.name, 'Alex');
    });
  });
});

Run the test:

npm test

Why Does Returning the Promise Matter?

Consider this version:

it('should return the correct user', function () {
  getUser().then((user) => {
    assert.equal(user.name, 'Alex');
  });
});

This test does not return the Promise or use done().

Mocha may consider the test complete as soon as the test function returns, before the Promise callback runs.

As a result, the assertion might execute after Mocha has already reported the test as successful. A later assertion failure may not be correctly associated with the test.

The correct version returns the Promise:

it('should return the correct user', function () {
  return getUser().then((user) => {
    assert.equal(user.name, 'Alex');
  });
});

Now Mocha waits for the Promise to settle.

If the Promise rejects or an assertion throws inside the .then() callback, the returned Promise rejects and Mocha reports the test as failed.

Method 3: Testing Async/Await in Mocha

The async/await syntax makes asynchronous JavaScript easier to read.

Instead of chaining multiple .then() callbacks, you can write asynchronous code in a style that resembles synchronous programming.

Mocha supports async test functions directly.

Consider the following example:

const assert = require('node:assert/strict');
const { getUser } = require('../userService');

describe('getUser()', function () {
  it('should return the correct user', async function () {
    const user = await getUser();

    assert.equal(user.id, 1);
    assert.equal(user.name, 'Alex');
  });
});

This is often the clearest approach for testing asynchronous functions.

How Does Async/Await Work?

Step 1: Declare the test as asynchronous.

async function () {

An async function returns a Promise.

Step 2: Wait for the operation.

const user = await getUser();

JavaScript waits for the Promise returned by getUser() to settle before continuing within the async function.

Step 3: Verify the result.

assert.equal(user.name, 'Alex');

The assertion runs after the user data has been retrieved.

Step 4: Let Mocha handle completion.

Mocha waits for the Promise returned by the async test function.

If the function throws an error or an awaited Promise rejects, the test Promise rejects and Mocha marks the test as failed.

You do not need to call done() in an async test.

Method 4: Testing Promise Rejections and Errors

Testing successful results is important, but your application must also handle failures correctly.

For example, a database query might fail, an API might return an error, or a user might request a resource that does not exist.

Mocha can test these situations by awaiting the relevant Promise and checking the resulting error.

Example: Testing a Rejected Promise

Consider this function:

function getUserById(id) {
  return new Promise((resolve, reject) => {
    if (id <= 0) {
      reject(new Error('Invalid user ID'));
      return;
    }

    resolve({
      id,
      name: 'Alex'
    });
  });
}

module.exports = { getUserById };

Now write a test for the invalid ID:

const assert = require('node:assert/strict');
const { getUserById } = require('../userService');

describe('getUserById()', function () {
  it('should reject when the user ID is invalid', async function () {
    await assert.rejects(
      getUserById(0),
      {
        message: 'Invalid user ID'
      }
    );
  });
});

This test passes when the Promise rejects with the expected error message.

If the Promise resolves instead, or rejects with a different error message, the assertion fails.

Testing a Synchronous Exception

Some functions throw errors immediately rather than returning rejected Promises.

You can test these functions with assert.throws():

const assert = require('node:assert/strict');

function divide(a, b) {
  if (b === 0) {
    throw new Error('Cannot divide by zero');
  }

  return a / b;
}

describe('divide()', function () {
  it('should throw when the divisor is zero', function () {
    assert.throws(
      () => divide(10, 0),
      {
        message: 'Cannot divide by zero'
      }
    );
  });
});

Use assert.rejects() for rejected Promises and assert.throws() for synchronous exceptions.

Method 5: Testing Functions With Timers

Timers are common in JavaScript applications. They may be used for delayed operations, retry logic, debouncing, and scheduled actions.

For example:

function delayedGreeting() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('Hello!');
    }, 1000);
  });
}

module.exports = { delayedGreeting };

You can test this function with async/await:

const assert = require('node:assert/strict');
const { delayedGreeting } = require('../timerService');

describe('delayedGreeting()', function () {
  it('should return the greeting after a delay', async function () {
    const result = await delayedGreeting();

    assert.equal(result, 'Hello!');
  });
});

Mocha waits for the Promise, so the test completes after the timer callback resolves it.

Avoid Unnecessarily Long Tests

A real one-second delay adds time to your test suite.

For functions involving timers, consider whether the timing itself is important to the test. In some situations, you can inject a timer or scheduler dependency and control it during testing.

When using timer-mocking tools, make sure the chosen library supports the relevant timer APIs and works correctly with your test environment.

For a basic asynchronous test, however, using the actual timer is often sufficient.

Method 6: Testing Multiple Asynchronous Operations

Applications often need to perform several asynchronous operations.

For example, a dashboard might retrieve user information and notifications independently.

You can test such functions using Promise.all().

Consider this example:

function getUser() {
  return Promise.resolve({
    id: 1,
    name: 'Alex'
  });
}

function getNotifications() {
  return Promise.resolve([
    'New message',
    'Profile updated'
  ]);
}

module.exports = {
  getUser,
  getNotifications
};

A test can await both operations:

const assert = require('node:assert/strict');
const {
  getUser,
  getNotifications
} = require('../dashboardService');

describe('Dashboard services', function () {
  it('should return user details and notifications', async function () {
    const [user, notifications] = await Promise.all([
      getUser(),
      getNotifications()
    ]);

    assert.equal(user.name, 'Alex');
    assert.equal(notifications.length, 2);
    assert.equal(notifications[0], 'New message');
  });
});

Promise.all() waits until all supplied Promises fulfill. If any of them rejects, the returned Promise rejects.

This makes it useful when operations can run independently and all results are required.

If you need to inspect every result even when some operations fail, Promise.allSettled() may be more appropriate.

Using Mocha Hooks With Asynchronous Code

Mocha provides hooks that run before or after tests.

These hooks are useful for setting up and cleaning up resources such as database connections, temporary files, and test data.

Common hooks include:

  • before() — runs once before the tests in a suite.

  • after() — runs once after the tests in a suite.

  • beforeEach() — runs before each test.

  • afterEach() — runs after each test.

Hooks can also use callbacks, Promises, or async/await.

For example:

const assert = require('node:assert/strict');

describe('Database tests', function () {
  let connected = false;

  before(async function () {
    await connectToDatabase();
    connected = true;
  });

  after(async function () {
    if (connected) {
      await disconnectFromDatabase();
    }
  });

  it('should use the database connection', async function () {
    const result = await getDatabaseStatus();

    assert.equal(result.connected, true);
  });
});

Here, connectToDatabase(), disconnectFromDatabase(), and getDatabaseStatus() represent application functions that would need to be implemented.

The before() hook waits for the database connection to complete before Mocha runs the tests. The after() hook waits for cleanup to finish.

Best practice: Ensure resources are cleaned up even when setup or a test fails. For complicated setups, use a clear ownership model for resource cleanup and consider registering cleanup as soon as a resource has been successfully acquired.

Common Mistakes in Mocha Async Testing

Even experienced developers can write asynchronous tests that pass unexpectedly or fail intermittently.

Here are some common mistakes and how to avoid them.

1. Forgetting to Return a Promise

Incorrect:

it('should fetch user data', function () {
  getUser().then((user) => {
    assert.equal(user.name, 'Alex');
  });
});

The test may finish before the Promise callback runs.

Correct:

it('should fetch user data', function () {
  return getUser().then((user) => {
    assert.equal(user.name, 'Alex');
  });
});

Alternatively, use async/await.

2. Using done() With Async/Await

Incorrect:

it('should fetch user data', async function (done) {
  const user = await getUser();

  assert.equal(user.name, 'Alex');
  done();
});

This combines two different completion mechanisms. Mocha reports an error when a test both accepts a done callback and returns a Promise, as an async function does.

Correct:

it('should fetch user data', async function () {
  const user = await getUser();

  assert.equal(user.name, 'Alex');
});

Use either done() or a returned Promise, not both.

3. Not Handling Callback Errors

Incorrect:

it('should get the message', function (done) {
  getMessage((error, message) => {
    assert.equal(message, 'Hello!');
    done();
  });
});

If the callback receives an error, the test does not handle it properly.

Correct:

it('should get the message', function (done) {
  getMessage((error, message) => {
    if (error) {
      return done(error);
    }

    try {
      assert.equal(message, 'Hello!');
      done();
    } catch (error) {
      done(error);
    }
  });
});

This ensures callback errors and assertion failures are reported to Mocha.

4. Forgetting to Await an Assertion

Incorrect:

it('should reject an invalid request', async function () {
  assert.rejects(getUserById(0));
});

The test does not wait for the asynchronous assertion to finish.

Correct:

it('should reject an invalid request', async function () {
  await assert.rejects(getUserById(0));
});

You can also return the Promise produced by assert.rejects().

5. Using Arbitrary Delays to Wait for Results

Incorrect:

it('should load user data', function (done) {
  setTimeout(() => {
    assert.ok(true);
    done();
  }, 2000);
});

This test waits for a fixed amount of time without actually verifying that the operation completed successfully.

Correct:

it('should load user data', async function () {
  const user = await getUser();

  assert.equal(user.name, 'Alex');
});

Waiting for the actual asynchronous operation is generally more reliable than guessing how long it will take.

6. Forgetting to Test Failure Cases

A function might work correctly when a request succeeds but behave incorrectly when the request fails.

Write tests for both successful results and expected failures, including rejected Promises, invalid input, and relevant external-service errors.

7. Leaving Resources Open

Database connections, network servers, and timers can keep a test process running after the tests finish.

Use Mocha hooks to clean up resources and make sure asynchronous cleanup is awaited.

If Mocha does not exit, investigate open handles rather than immediately forcing the process to terminate.

Best Practices for Mocha Async Testing

Follow these practices to create reliable asynchronous tests.

1. Prefer Async/Await for Readability

For most Promise-based functions, async/await makes tests easier to read and maintain.

it('should return the correct result', async function () {
  const result = await fetchResult();

  assert.equal(result.status, 'success');
});

2. Keep Tests Independent

Each test should ideally run without depending on another test's execution order.

Create isolated test data and clean up resources to reduce unexpected failures.

3. Test Success and Failure Scenarios

Verify expected results, rejected Promises, invalid input, and other relevant error conditions.

This helps confirm that the application behaves correctly in more than one situation.

4. Use Appropriate Timeouts

Mocha has a default timeout for tests and hooks. An operation that takes longer than the configured timeout can cause the test to fail.

For example:

it('should complete a slow operation', async function () {
  this.timeout(5000);

  const result = await slowOperation();

  assert.equal(result.status, 'completed');
});

This example increases the timeout to five seconds.

Use longer timeouts only when justified. Increasing the timeout does not fix a test that never resolves.

5. Avoid Unnecessary Real Network Calls

Tests that depend on external APIs can become slow or unreliable because of network failures, rate limits, or service outages.

Where practical, mock or stub external dependencies when testing application logic.

Use separate integration tests when you need to verify communication with a real service.

6. Use Clear Test Names

Write test descriptions that explain the expected behavior.

For example:

it('should reject when the user ID is invalid', async function () {
  await assert.rejects(getUserById(0));
});

Clear names make test failures easier to understand.

7. Use the Right Assertion Library

Node.js includes a built-in assertion module:

const assert = require('node:assert/strict');

You can also use libraries such as Chai if your project requires their assertion styles.

Choose one approach and keep the tests consistent.

When Should You Use Mocha for Async Testing?

Mocha is useful when your JavaScript or Node.js application includes asynchronous operations that need reliable automated tests.

Common use cases include:

  • Testing REST API endpoints

  • Testing database service functions

  • Verifying authentication workflows

  • Testing file operations

  • Checking asynchronous utility functions

  • Testing background jobs

  • Validating error-handling logic

Mocha is flexible and can work with many assertion and mocking libraries.

However, Mocha is not the only testing framework available. Depending on the project, developers may also consider Jest, Vitest, or Node.js's built-in test runner.

The best choice depends on the project's requirements, existing tooling, and team preferences.

Frequently Asked Questions

1. What Is Async Testing in Mocha?

Async testing in Mocha verifies functions that complete after an asynchronous operation. Mocha supports callbacks, returned Promises, and async/await so tests can wait for operations to finish.

2. How Do You Test Async Functions in Mocha?

Declare the test function as async and use await to wait for the asynchronous operation.

it('should return user data', async function () {
  const user = await getUser();

  assert.equal(user.name, 'Alex');
});

Mocha waits for the Promise returned by the async test function.

3. What Is the done() Function in Mocha?

done() is a callback used to tell Mocha that an asynchronous test has finished. Call done() when the operation succeeds and done(error) when it fails.

It is mainly useful for callback-based asynchronous code.

4. Can Mocha Test Promises?

Yes. Mocha supports Promises directly. Return a Promise from the test function, and Mocha waits for it to settle.

If the Promise rejects, Mocha reports the test as failed.

5. What Is the Difference Between done() and async/await?

done() is a callback-based completion mechanism. async/await works with Promises and allows asynchronous code to be written in a more readable style.

Use one completion mechanism per test.

6. How Do You Test Errors in Mocha?

For synchronous errors, use assertions such as assert.throws(). For rejected Promises, use assert.rejects() and make sure you await or return the assertion's Promise.

7. Why Is My Mocha Async Test Passing Before the Operation Finishes?

This commonly happens when a test starts an asynchronous operation but neither returns its Promise nor calls done() after completion.

Return the Promise, use async/await, or use the done callback for callback-based code.

8. How Do I Increase the Mocha Timeout?

You can set a timeout for an individual test:

it('should finish a long operation', async function () {
  this.timeout(5000);

  await longOperation();
});

You can also configure timeouts through Mocha's command-line options or configuration file.

9. Can I Use Mocha With Node.js?

Yes. Mocha is commonly used to test Node.js applications, including asynchronous services, API logic, database operations, and utility functions.

10. Is Mocha Better Than Jest for Async Testing?

Neither is universally better. Both support asynchronous testing. Mocha offers flexibility in choosing assertion and mocking libraries, while Jest includes more testing functionality out of the box.

The right choice depends on your project and testing requirements.

Conclusion

Asynchronous testing is essential for building reliable Node.js applications, especially when working with APIs, databases, timers, and file operations.

Mocha makes asynchronous testing possible through callbacks, Promises, and async/await. By understanding these approaches, you can verify successful results, test error handling, and prevent asynchronous operations from completing unnoticed.

In this guide, you learned how to set up Mocha, write callback-based tests, test Promises, use async/await, handle rejected Promises, work with hooks, and avoid common mistakes.

For most modern Promise-based code, async/await provides a clear and readable testing style. For callback-based APIs, Mocha's done() callback remains useful.

The key to reliable asynchronous tests is simple: make sure Mocha knows when the operation has completed, and ensure every failure is reported correctly.

Start by writing a few tests for your existing asynchronous functions, then gradually expand your test suite to cover edge cases, error scenarios, and integration workflows.

D
DevByteAuthor

Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.

Keep Exploring

Related Engineering Dispatches

More guides and architectural patterns you might find valuable.

Browse All Articles↘