Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
187
rated 0 times [  190] [ 3]  / answers: 1 / hits: 75726  / 10 Years ago, fri, february 28, 2014, 12:00:00

I am using Mocha in order to unit test an application written for Node.js.


I wonder if it's possible to unit test functions that have not been exported in a module.


Example:


I have a lot of functions defined like this in foobar.js:


function private_foobar1(){
...
}

function private_foobar2(){
...
}


And a few functions exported as public:


exports.public_foobar3 = function(){
...
}

The test case is structured as follows:


describe("private_foobar1", function() {
it("should do stuff", function(done) {
var stuff = foobar.private_foobar1(filter);
should(stuff).be.ok;
should(stuff).....

Obviously this does not work, since private_foobar1 is not exported.


What is the correct way to unit-test private methods? Does Mocha have some built-in methods for doing that?


More From » node.js

 Answers
42

If the function is not exported by the module, it cannot be called by test code outside the module. That's due to how JavaScript works, and Mocha cannot by itself circumvent this.


In the few instances where I determined that testing a private function is the right thing to do, I've set some environment variable that my module checks to determine whether it is running in a test setup or not. If it runs in the test setup, then it exports additional functions that I can then call during testing.


The word "environment" is loosely used here. It might mean checking process.env or something else that can communicate to the module "you're being tested now". The instances where I've had to do this were in a RequireJS environment, and I've used module.config for this purpose.


[#72241] Thursday, February 27, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianod

Total Points: 667
Total Questions: 106
Total Answers: 92

Location: Jordan
Member since Thu, Aug 5, 2021
3 Years ago
lucianod questions
;