Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unit test non-exported functions?

In a JavaScript ES6-module, there may be many, small, easy-to-test functions that should be tested, but shouldn't be exported. How do I test functions in a module without exporting them? (without using Rewire).

like image 989
Jordan Avatar asked Jan 09 '19 18:01

Jordan


People also ask

How do you test a function without exporting it?

Testing the non-exported function by testing the function(s) that use it is not really unit-testing. I agree that "private functions are an implementation detail" and it's not them that they need to be tested, but the behaviour of your publicly available function, class or whatever you have at hand.

How do you test if a function has been called in jest?

To check if a component's method is called, we can use the jest. spyOn method to check if it's called. We check if the onclick method is called if we get the p element and call it.

How many exports can a module have?

A module can have one and only one default export.

How do module exports work?

All functions related to a single module are contained in a file. Module exports are the instructions that tell Node. js which bits of code (functions, objects, strings, etc.) to export from a given file so that other files are allowed to access the exported code.


3 Answers

Export an "exportedForTesting" const

function shouldntBeExportedFn(){
  // Does stuff that needs to be tested
  // but is not for use outside of this package
}

export function exportedFn(){
  // A function that should be called
  // from code outside of this package and
  // uses other functions in this package
}

export const exportedForTesting = {
  shouldntBeExportedFn
}

The following can be used in production code:

import { exportedFn } from './myPackage';

And this can be used in unit tests:

import { exportedFn, exportedForTesting } from './myPackage';
const { shouldntBeExportedFn } = exportedForTesting;

This strategy retains the context clues for other developers on my team that shouldntBeExportedFn() should not be used outside of the package except for testing.

I've been using this for years, and I find that it works very well.

like image 97
Jordan Avatar answered Oct 06 '22 23:10

Jordan


I wish I had a better answer for you, Jordan. 😊 I had very similar question in both JavaScript and C# contexts in the past...

Answer / not answer

At some point I had to embrace the fact that if I want granular unit tests that cover unexported/private functions/methods, I really should expose them. Some people would say that it's a violation of encapsulation, yet others disagree with that. The former group of people would also say that until a function is exported/public, it's essentially an implementation detail, thus should not be unit-tested.

If you're practicing TDD then Mark Seeman's explanation should be relevant (Pluralsight), and hopefully it will clarify why it's okay to expose things.

I don't know if you can find some trick for invoking the unexported functions directly from your unit tests without making changes to the code under test, but I would not go that way personally.

Just an option

Another option is to split your library into two. Say, library A is your application code, and library B is the package that contains all those functions you would like to avoid exporting from A's interface.

If they are two different libraries, you can control on a very fine level what is exposed and how it is tested. Library A will just depend on B without leaking any of the B's details. Both A and B are then testable independently.

This will require different code organization, sure, but it will work. Tools like Lerna simplify multi-package repositories for JavaScript code.

Side note

I don't agree with AlexSzabó, to be honest. Testing the non-exported function by testing the function(s) that use it is not really unit-testing.

like image 9
Igor Soloydenko Avatar answered Oct 07 '22 00:10

Igor Soloydenko


I know this already has an answer, but I didn't like the answer selected because it involves having extra functions. :) After some research lead me to https://www.jstopics.com/articles/javascript-include-file (so basic idea can be found there and credit to him/her). My code is Typescript, but this should work for normal Javascript too.

Assuming your source app is in "app.ts" and you have a private function called "function1":

// existing private function, no change here
function function1(s :string) :boolean => {
  let result=false; /* code, result=true if good */ return result;
}

// at bottom add this new code
 
// exports for testing only
// make the value something that will never be in production
if (process.env['NODE_DEV'] == 'TEST') {
    module.exports.function1 = function1;
    module.exports.function2 = function2; // add functions as needed
}

I'm using Jest to do unit testing, so in tests/app.test.ts we do:

process.env['NODE_DEV'] = 'TEST';
let app = require("../app");

describe("app tests", () => {
  test('app function1', () => {
    expect(app.function1("blah")).toBe(true);
    expect(app.function1("foo")).toBe(false);
  });

  test('app function2', () => {
    expect(app.function2(2)).toBeUndefined();
  });
});

Add whatever tests you need and it will test those private functions. It works for me without needing Rewire.

like image 3
kbrannen Avatar answered Oct 06 '22 23:10

kbrannen