# Nodejs Unit Tests With Mocha

Setting up a Node.js project for unit testing involves several steps, including project initialization, installing necessary dependencies, and configuring your test environment. Here's a detailed guide:

# 1. Initialize a Node.js Project

First, create a new directory for your project and initialize it with npm:

mkdir my-node-project
cd my-node-project
npm init -y

The -y flag automatically answers "yes" to all prompts, generating a package.json file with default settings.

# 2. Install Testing Frameworks

There are several testing frameworks you can choose from, but some of the most popular are:

  • Mocha: A flexible and widely-used test framework.
  • Jest: A popular testing framework maintained by Facebook, which includes a test runner, assertion library, and more.
  • Chai: An assertion library that works well with Mocha.

For this example, we'll use Mocha and Chai:

npm install --save-dev mocha chai

# 3. Set Up the Project Structure

Organize your project structure as follows:

my-node-project/
│
├── src/
│   └── index.js
├── test/
│   └── index.test.js
├── node_modules/
├── package.json
└── .gitignore
  • src/: Contains your application code.
  • test/: Contains your test files.
  • node_modules/: Directory where npm installs your dependencies.
  • package.json: Your project's metadata and dependencies.
  • .gitignore: A file to exclude certain files and directories from version control.

# 4. Write a Simple Test

In test/index.test.js, write a simple test case. For example:

const chai = require('chai');
const expect = chai.expect;

const { add } = require('../src/index');

describe('Addition', () => {
    it('should return 4 when adding 2 + 2', () => {
        const result = add(2, 2);
        expect(result).to.equal(4);
    });
    it('should return 8 when adding 2 + 6', () => {
        const result = add(2, 6);
        expect(result).to.equal(8);
    });
});

# 5. Write the Application Code

Create a simple function to be tested in src/index.js:

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

module.exports = { add };

# 6. Configure the Test Script

In package.json, add a test script to run Mocha:

"scripts": {
  "test": "nyc mocha test/**/*.test.js"
}

# 7. Run Your Tests

Now, you can run your tests using the following command:

$ npm test

> ut@1.0.0 test
> nyc mocha test/**/*.test.js



  Addition
    ✔ should return 4 when adding 2 + 2
    ✔ should return 8 when adding 2 + 6


  2 passing (6ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |                   
 index.js |     100 |      100 |     100 |     100 |                   
----------|---------|----------|---------|---------|-------------------

You should see output from Mocha indicating whether your tests passed or failed.

# 8. Optional: Set Up a Watcher

You can set up a watcher to automatically run tests when files change. For this, you can use nodemon or mocha with the --watch flag:

npm install --save-dev nodemon

Update the test script in package.json:

"scripts": {
  "test": "mocha --watch"
}

# 9. Optional: Integrate with CI/CD

If you plan to integrate your tests with a Continuous Integration (CI) service like GitHub Actions, CircleCI, or Travis CI, ensure that the npm test command runs your tests during the CI process.

# 10. Add More Tests

As your application grows, continue to add more tests under the test/ directory, ensuring you cover various edge cases and scenarios.

Now you have a basic Node.js project set up with Mocha and Chai for unit testing!

# Issues

# nyc command not found

npm install nyc

# Exception during run: Error [ERR_REQUIRE_ESM]: require() of ES Module

Checked the Chai Releases (opens new window), it has breaking changes in version 5.0.0:

  • Chai now only supports EcmaScript Modules (ESM). This means your tests will need to either have import {...} from 'chai' or import('chai'). require('chai') will cause failures in nodejs. If you’re using ESM and seeing failures, it may be due to a bundler or transpiler which is incorrectly converting import statements into require calls.
  • Dropped support for Internet Explorer.
  • Dropped support for NodeJS < 18.
  • Minimum supported browsers are now Firefox 100, Safari 14.1, Chrome 100, Edge 100. Support for browsers prior to these versions is “best effort” (bug reports on older browsers will be assessed individually and may be marked as wontfix).

# Code

Please check the code in GitHub (opens new window).

Last Updated: 8/11/2024, 1:16:14 PM