Testing TypeScript function which is not exported
While it is not possible to access non-exported function directly there is still a way to export them in a "semi-hidden" way. One possible approach would be:
// In your library module declare internal functions as non-exported like normal.
function someInternalFunctionA(x: number): number {
return x;
}
function someInternalFunctionB(x: number): number {
return x;
}
// At the bottom, offer a public escape hatch for accessing certain functions
// you would like to be available for testing.
export const _private = {
someInternalFunctionA,
someInternalFunctionB,
};
On test side you can do:
import { _private } from "./myModule";
test("someInternalFunctionA", () => {
expect(_private.someInternalFunctionA(42)).toEqual(42);
});
What I like about the approach:
- No need to mark
someInternalFunctionA
withexport
directly. - It should still be very obvious that the stuff under
_private
isn't officially part of the public interface.
There is no way to access a non-exported module function.
module MyModule {
function privateFunction() {
alert("privateFunction");
}
}
MyModule.privateFunction(); // Generates a compiler error
However, leaving aside the question of validity of private method testing, here is what you can do.
Group your functions into an utility class, and then leverage the fact that private class members can be accessed via square bracket notation.
module MyModule {
export class UtilityClass {
private privateFunction() {
alert("privateFunction");
}
}
}
var utility = new MyModule.UtilityClass();
//utility.privateFunction(); Generates a compiler error
utility["privateFunction"](); // Alerts "privateFunction"