Is There A Way To Test Functions With Jasmine Without Exposing Them?

- 1 answer

I have a utils.js file with some generic utility functions. I use module.exports to expose some of the functions while keep the rest hidden.

module.exports = {
utils_1: function_1,
utils_2: function_2

Suppose there are other functions, namely function_3 and function_4 that I would like not to expose, yet I want to test with Jasmine. The only way I can currently do it is by exposing them with the rest of the functions and writing my test suites as usual.

Is there a way to test some functions via Jasmine while not exposing them?

The only thing I can think of is creating a different javascript file containing (and exposing) function_3 and function_4, require that file in my utils.js and at the same time test the new file with Jasmine, but this would split my original file in two (and the same would apply for all other similar files).



function_3 and function_4 are used inside function_1 and function_2, right? So, do you really need to unit test it? I would not. But other people might think the contrary.

Here is my example

// utils.js
function function_3(obj) {
  obj.a = 3;
  return obj;

function function_4(obj) {
  obj = function_3(obj); // invoke function_3
  obj.b = 4;
  return obj;
module.exports = { utils_4: function_4 };

The test:

const { utils_4 } = require('utils');

describe('test 1', () => {
  it('should pass', () => {
    const obj = utils_4 ({});



It should pass, right? See that I only test function_4, but, if I change the implementation of function_3 in a way that brakes my test, the test will detect it.

If we change function_3 to

function function_3(obj) {
  obj.c = 3;
  return obj;

The test will fail.

This is an awful example but it is just illustrative. Take the good part of it. But again, other people might think the contrary and will go with an approach to test function_3 directly. Use a coverage lib to see what is covered by your tests.

Hope it helps