How to test private function using mocha?

Member

by jerad , in category: Javascript , 18 days ago

How to test private function using mocha?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 18 days ago

@jerad 

To test a private function using Mocha, you can use a technique called function hoisting. This involves defining the private function within the scope of the module function and then exporting the module function for testing. Here's how you can do it:

  1. Define the private function within the module function:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
function myModule() {
  function privateFunction(param) {
    return param * 2;
  }

  function publicFunction(param) {
    return privateFunction(param);
  }

  return {
    publicFunction
  };
}

module.exports = myModule;


  1. In your test file, import the module function and test the public function that calls the private function:
1
2
3
4
5
6
7
8
9
const assert = require('assert');
const myModule = require('./myModule');

describe('myModule', () => {
  it('should return the result of privateFunction', () => {
    const result = myModule().publicFunction(5);
    assert.strictEqual(result, 10);
  });
});


By testing the public function that calls the private function, you can indirectly test the private function as well. Note that this approach may not work for all scenarios, especially if the private function has its own logic that you need to test separately. In that case, you may need to use a different testing approach, such as using a code coverage tool like Istanbul to verify that the private function is being executed as expected.