How to unit test node.js functions with mocha?

Member

by rollin , in category: Javascript , 4 months ago

How to unit test node.js functions with mocha?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by giovanny.lueilwitz , 4 months ago

@rollin 

To unit test Node.js functions using Mocha, you can follow these steps:

  1. Install Mocha and any other necessary testing libraries:
1
npm install mocha chai


  1. Create a test file for your Node.js functions. For example, if you have a function in a module called example.js, create a example.test.js file in the same directory.
  2. In your test file, import the necessary modules and functions:
1
2
const assert = require('chai').assert;
const example = require('./example');


  1. Write test cases using Mocha's describe and it functions. For example:
1
2
3
4
5
6
7
8
9
describe('Example', function() {
  it('should return the sum of two numbers', function() {
    assert.equal(example.add(1, 2), 3);
  });

  it('should return the difference of two numbers', function() {
    assert.equal(example.subtract(5, 3), 2);
  });
});


  1. Run your tests by running Mocha in the terminal:
1
./node_modules/.bin/mocha


Alternatively, you can add a script to your package.json file to run the tests:

1
2
3
"scripts": {
  "test": "mocha"
}


Then you can run your tests using:

1
npm test


  1. Analyze the output of Mocha to see if your tests passed or failed.


By following these steps, you can effectively unit test your Node.js functions using Mocha.