TL;DR: So you got yourself into a mess. and you did not follow TDD or any of the SOLID rules you did not write pure functions and now you want to test some private function. I got your back lol. Typescript will prevent you from trying to execute them private/hidden functions, but you can still run them. Somewhere a million OOP developers just had their minds blown. 😤

Why are you trying to hide them functions?

You might have some good reasons, but make sure they are the right ones. Are you creating a public interface for others to use? If so then you have a very good reason to hide the private functions. Or do you just need to expose the correct interface and have private modules?

Adding ts-ignore in your tests

Just use the notation shown below or the fab @ts-ignore. 😅

You can even just use the “as any” method!!

    object["functionName"](args);  😛

    // @ts-ignore 😇
    object.functionName(args)
    
    (thing as any).functionName(args)

Understand the sacrifice/trade-off

You might want to consider

  1. Are you happy just to make the private function a public function? ( for the sake of testing )
  2. Are you sure that the function does not belong to another class? and should be public?
  3. Is it a pure function? Can it go in a module?
  4. Are you happy to execute your function using the [“function-name”] method as shown above and do you understand the consequences of that?

The real question is “How hard do you want to make your life?”

If you want to make things hard for yourself, and you have no choice but to write tests for your code ( Because your team/organisation has dictated that ), and you don’t like any of the options above. Then it comes down to this :

You will have to test “function A” via the public interface of the object, which might be “function C”. Some times it’s much simpler to just test that private function. But then again are you testing it twice? It may end up being a judgement call on the pro’s and cons.

Testing a private function via a public interface is difficult, or a least it can be.

That is going to be “very hard” ( perhaps ), your tests might be brittle, and when the tests fail you will not know why, as it could be in one of those other private functions that you are trying so very hard to hide.

Under the hood, javascript does not really have private functions/methods.