1

I believe everyone encounters a case when there's necessity to test internal wiring of the class/object. I know that in compiled languages this could be done through conditional compiling. Is this what I should do for JavaScript as well? What's the usual way to accomplish such task? Maybe I should just treat the class/object as a Black Box and only test it's outcomes?

jayarjo
  • 16,124
  • 24
  • 94
  • 138

1 Answers1

2

Testing object's public contract (ie. black box testing you mentioned) most of the times should be enough. Proper test coverage of public members should exercise majority of private/internals as well. After all, why would user of your class (be it other programmer, other objects/collaborators) care about what your objects do inside?

When you arrive at the point that you feel a strong need of testing internals, treat it as an opportunity to improve. Usually, such need is a result of your code communicating you something - "maybe I shouldn't be private", "maybe it's worth to refactor me into separate being".

Also, keep in mind that testing internals makes your tests more fragile. While your object/class functionality (contract) might remain the same, implementation might change fairly often. Think about replacing your own pieces of code with 3rd party/external libraries (quite common change) - is this a reason to break your tests? It is not.

I realize sometimes you just have to test internals - but IMO, it's better to stop then and think whether you can make your code better (very often you'll find out you indeed can!). Treat testing internals as a last resort when everything else failed.

Community
  • 1
  • 1
k.m
  • 30,794
  • 10
  • 62
  • 86