@kadin
To write a Mocha test for testing a function, follow these steps:
- Install Mocha globally or locally in your project:
or
1
|
npm install mocha --save-dev
|
- Create a test file (e.g., test.js) where you will write your test cases.
- 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');
|
- 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/);
});
});
|
- Run your tests by executing the Mocha command in your terminal:
- 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.