How to write a mocha test testing a function?

Member

by kadin , in category: Javascript , 17 days ago

How to write a mocha test testing a function?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by edmond_brakus , 16 days ago

@kadin 

To write a Mocha test for testing a function, follow these steps:

  1. Install Mocha globally or locally in your project:
1
npm install -g mocha


or

1
npm install mocha --save-dev


  1. Create a test file (e.g., test.js) where you will write your test cases.
  2. Require the function you want to test and any other necessary modules at the top of your test file:
1
2
const assert = require('assert');
const myFunction = require('./myFunction');


  1. Write your test cases using the Mocha testing framework syntax. Here's an example test for a function that adds two numbers:
1
2
3
4
5
6
7
8
9
describe('myFunction', function () {
    it('should return the sum of two numbers', function () {
        assert.equal(myFunction.add(2, 3), 5);
    });
    
    it('should return an error for invalid inputs', function () {
        assert.throws(() => myFunction.add('a', 3), /Invalid input/);
    });
});


  1. Run your tests by executing the Mocha command in your terminal:
1
mocha test.js


  1. View the test results in your terminal to see if the function passed all the test cases.


You can add more test cases to cover different scenarios and edge cases for your function. Mocha provides several assertion methods like assert.equal(), assert.strictEqual(), assert.throws(), etc., that you can use to test different aspects of your function.