0
0
NodejsHow-ToBeginner · 3 min read

How to Use Mocha with Node.js: Simple Testing Guide

To use Mocha with Node.js, first install Mocha using npm install --save-dev mocha. Then, write test files using Mocha's syntax and run tests with the mocha command in your terminal.
📐

Syntax

Mocha uses a simple syntax with describe blocks to group tests and it blocks for individual test cases. Inside it, you write assertions to check your code's behavior.

  • describe('description', function() { ... }): Groups related tests.
  • it('should do something', function() { ... }): Defines a single test case.
  • Use assertion libraries like assert or chai inside it to verify outcomes.
javascript
const assert = require('assert');
describe('Array', function() {
  it('should return -1 when value is not present', function() {
    assert.strictEqual([1, 2, 3].indexOf(4), -1);
  });
});
💻

Example

This example shows a simple test for a function that adds two numbers. It demonstrates how to write a test file and run it with Mocha.

javascript
const assert = require('assert');

function add(a, b) {
  return a + b;
}

describe('add function', function() {
  it('should return sum of two numbers', function() {
    assert.strictEqual(add(2, 3), 5);
  });

  it('should return a number', function() {
    assert.strictEqual(typeof add(2, 3), 'number');
  });
});
Output
add function ✓ should return sum of two numbers ✓ should return a number 2 passing (10ms)
⚠️

Common Pitfalls

Common mistakes when using Mocha include:

  • Not installing Mocha locally or globally before running tests.
  • Forgetting to export functions or modules you want to test.
  • Using asynchronous code without calling done() or returning a promise.
  • Running tests with node instead of mocha command.

Always run tests using npx mocha or add a test script in package.json.

text
/* Wrong: running test file directly with node */
// node test.js

/* Right: run tests with mocha */
// npx mocha test.js
📊

Quick Reference

CommandDescription
npm install --save-dev mochaInstall Mocha as a development dependency
npx mochaRun all test files in the test folder
describe(description, fn)Group related tests
it(description, fn)Define a single test case
assert.strictEqual(actual, expected)Check if actual equals expected

Key Takeaways

Install Mocha locally with npm before writing tests.
Use describe and it blocks to organize and write tests.
Run tests using the mocha command, not node.
Handle asynchronous tests properly with done or promises.
Use assertion libraries like assert for checking results.