Search code examples
javascriptecmascript-6jestjses6-modules

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).


Solution

  • 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.