How can I unit test non-exported functions?

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.


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.