4

I have a function that has inner functions, for my unit test, I only want to test the functionality of the inner function, but when I export the function and call the inner function, npm tests returns an error.

In my main.js:

mainFunction = () => {
  functionToBeTested = () => {
    // some code
  }
}

module.exports = {mainFunction: mainFunction}

In my test.js

const chai    = require("chai");
const assert  = require("chai").assert;
const mainFunction = require("./main");

describe ("test", () => {
 it("returns results", () => {
  let result = mainfunction.functionToBeTested(args);
  //equal code
  });
})

But when I run npm test, it says:

mainfunction.functionToBeTested is not a function.

What am I doing wrong?

Wyck
  • 10,311
  • 6
  • 39
  • 60
Ken Shang
  • 41
  • 2
  • Where do you actually declare the function to be tested? is it the declaration within mainFunction? Perhaps mainFunction should call this function, but not declare it. If the function isn't declared in mainFunction, I don't see it declared anywhere. – JosephDoggie Jul 15 '19 at 13:22
  • 2
    Relevant commentary about whether or not you should actually test inner/private functions at all: https://stackoverflow.com/questions/105007/should-i-test-private-methods-or-only-public-ones – Wyck Jul 15 '19 at 14:09

3 Answers3

3

If you want to chain your functions you can try something like that.

main.js

const mainFunction = () => {
  const functionToBeTested = () => {
    return "I got it";
  }
  return { functionToBeTested };
}

module.exports = { mainFunction };

test.js

const chai    = require("chai");
const assert  = require("chai").assert;
const mainFunction = require("./main");

const mf = mainFunction();

describe ("test", () => {
 it("returns results", () => {
  let result = mf.functionToBeTested(args);
    //equal code
  });
});
zronn
  • 1,026
  • 8
  • 26
2

Actually, you can't call a function declare inside another function that way. A solution would be to declare functionToBeTested outside mainFunction, then call it :

main.js

const functionToBeTested = () => {
  // some code
};

const mainFunction = () => {
  functionToBeTested();
};

module.exports = { mainFunction, functionToBeTested }

test.js

const chai    = require("chai");
const assert  = require("chai").assert;
const { mainFunction, functionToBeTested } = require("./main");

describe ("test", () => {
  it("tests mainFunction", () => {
    let main = mainfunction(args);
    ...
  });

  it("tests functionToBeTested"), () => {
    let tested = functionToBeTested(args);
    ...
  });
})
zronn
  • 1,026
  • 8
  • 26
1

It is because only mainFunction() is exported and not the functionToBeTested(), outside this module JS doesn't knows about the existence of the functionToBeTested().

I will recommend you to move functionToBeTested separated and export that as well or have a helper method for calling it.