Lattes

Latte recipes, espresso drinks and coffee how-to

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

How to Test a Node.js Module with Mocha and Assert

· 4 min read · Espresso Drinks

Testing is the backbone of reliable software development, ensuring that your code behaves as expected even as it evolves. By combining Mocha, a flexible test framework, with Node.js’s built-in assert module, you can create robust unit tests without adding heavy external dependencies. This guide walks you through setting up a testing environment, writing clear assertions, and running your suite efficiently.

What You'll Need

  • A project initialized with Node.js (run npm init -y if you haven't already).
  • Mocha installed as a dev dependency (npm install --save-dev mocha).
  • Your source code module ready for testing (e.g., mathUtils.js).
  • Familiarity with basic JavaScript syntax and ES modules or CommonJS imports.

Step-by-Step

  1. Create your source module. Start by writing the function you want to test. For example, create a file named mathUtils.js containing a simple addition function:
    function add(a, b) {
      return a + b;
    }
    module.exports = { add };
  2. Set up the test directory. It is best practice to keep tests separate from source code. Create a folder named test in your project root. Inside this folder, create a file named mathUtils.test.js.
  3. Import necessary modules. In your test file, require Mocha's describe/it blocks and Node's assert module. Since we are using CommonJS, use const:
    const { describe, it } = require('mocha');
    const assert = require('assert');
    const { add } = require('../mathUtils');
  4. Structure your test suite. Use describe to group related tests. This helps organize output when running multiple tests. Wrap your tests in a block like this:
    describe('Math Utils', () => {
      // Tests go here
    });
  5. Write individual test cases. Inside the describe block, use it to define specific scenarios. The first argument is a string describing what should happen, and the second is a function containing your logic.
      it('should add two positive numbers correctly', () => {
        const result = add(2, 3);
        assert.strictEqual(result, 5);
      });
  6. Add edge case tests. Good testing covers boundaries. Add tests for zero, negative numbers, and non-numbers to ensure your function handles them gracefully or throws errors as expected.
      it('should handle negative numbers', () => {
        assert.strictEqual(add(-1, -1), -2);
      });
    
      it('should throw error on invalid input', () => {
        assert.throws(() => add('a', 2), TypeError);
      });
  7. Configure npm scripts. Open your package.json and add a test script to run Mocha easily:
    "scripts": {
      "test": "mocha"
    }
  8. Run the tests. Execute npm test in your terminal. Mocha will automatically find files ending in .test.js or .spec.js inside the test directory and execute them.

Common Mistakes

One frequent error is forgetting to export the functions you intend to test. If your module uses default exports or class-based structures, ensure your import statement matches exactly. Another common pitfall is mixing synchronous and asynchronous logic incorrectly; if your function returns a Promise, you must use async/await or return the promise in your test callback, otherwise Mocha won't know when the test finishes.

Tips

Use assert.strictEqual rather than == to avoid type coercion bugs. This ensures both value and type match. Additionally, leverage Mocha's beforeEach hook to reset state between tests, keeping them isolated and independent. Isolated tests prevent side effects where one test inadvertently changes data needed by another.

Troubleshooting

If Mocha reports "no tests found," check your file naming convention. Ensure your test files end in .js and are located in a directory Mocha can access. If you see "ReferenceError: require is not defined," you may be using ES Modules (import) but trying to use CommonJS syntax. Switch to dynamic imports or configure Mocha to support ESM. If tests pass unexpectedly, verify you aren't catching errors silently; let assertions fail visibly so you catch regressions early.

Frequently Asked Questions

Can I use Mocha with other assertion libraries?

Yes, while this guide uses Node's built-in assert, Mocha works seamlessly with Chai, Should.js, and others. You simply replace the require statement for assert with your chosen library.

How do I test asynchronous functions?

Mark your test callback as async and await the result, or return the promise directly. Mocha waits for promises to resolve before marking the test as complete.

Why are my tests running twice?

This usually happens if you have duplicate file patterns in your Mocha configuration or if you accidentally include the test directory in your main source watch list. Check your package.json scripts for overlapping paths.

Is it necessary to test every single function?

Not necessarily. Focus on business logic, complex calculations, and public APIs. Simple getters/setters or trivial utility functions often don't require dedicated unit tests unless they contain critical branching logic.

How do I mock external dependencies?

For mocking, consider using libraries like Sinon.js alongside Mocha. They allow you to replace real database calls or API requests with fake responses during testing.