1

I'm using Jest 24 with my Angular 8 app.

When a try to test a private function on a component, a TS2341 error is thrown. Something like :

error TS2341: Property 'myFunction' is private and only accessible within class 'MyClass'

Is there a way to ignore or fix that ?

I already find the "// @ts-ignore" solution, but it's so ugly !

Thanks all !

skyboyer
  • 22,209
  • 7
  • 57
  • 64
j.2bb
  • 881
  • 3
  • 10
  • 17
  • 1
    *Don't* test private methods? The compiler's telling you the right thing; that is (or ought to be) an *implementation detail*. – jonrsharpe Apr 26 '20 at 11:34
  • 2
    @jonrsharpe : I understand your point of view. However, I use a lot of private methods to cut my code and thus be able to test my functions more easily. These functions are only used internally in the class, so it would be a shame to make them public only for unit tests. And for all that, testing only the public method (the one that calls the private methods) would make the cutting unnecessary. – j.2bb Apr 26 '20 at 11:53
  • I don't know what you mean by *"cut my code"*. Maybe it *is* unnecessary. Test through public interfaces. – jonrsharpe Apr 26 '20 at 11:54
  • 1
    Sorry for my translation :) "cut my code" = "create manageable chunks" – j.2bb Apr 26 '20 at 12:01
  • 1
    Private methods are a perfectly good way to factor out logic and make the code easier to follow. That *doesn't* mean you should test them directly, because they'll still get invoked when you call the public methods you factored them out of. And doing that doesn't make the refactor redundant, because the code is still more readable. Test *behaviour*, not implementation. – jonrsharpe Apr 26 '20 at 12:05
  • Ok, I see what you mean, thank you ;) – j.2bb Apr 26 '20 at 12:07

2 Answers2

0

Usually, we do not need to test private methods. There should be a public method or template value that uses that private method. So you can test that to validate your private method.

Example --

public methodA(){
  valueB = methodB()
  // do something with valueB
  valueC = doSomthing(valueB)
  return valueC
}

private methodB() {
  return valueB
}

You can test methodA then methodB is automatically tested.

0

You can cast to any, but that's ugly, too:

(MyClass as any).myFunction
Galdor
  • 1,636
  • 4
  • 23
  • 37