There’s some debate as to whether or not you should test private members in a class. Generally, I fall in to the “if it makes sense to test it, test it” camp. If there’s a private method that is only accessible by a hard-to-mock series of callbacks or events, I would much rather write a bunch of tests to check the private method containing the logic than splitting it out into a different class or setting up the chain of events that would naturally call it.
So, since I’m a fan of liberal testing, here’s how you can access private stuff on your TypeScript classes.
Its just Javascript
Since TypeScript is just Javascript, and Javascript has no notion of “public” or “private”, it is actually pretty straightforward to access “private” members. The TypeScript compiler won’t like you if you try and access the private members directly, but you can still use a property accessor to get at them:
Testing
If you want to spyOn a method of a class, you run into the same problem as before – The TypeScript compiler will balk at the idea of spying on a private method. Fortunately, you can cast the spy as <any> and it will let you do whatever you want!
Note
Of course, this is a little dangerous. Using magic strings to reference properties and casting things to <any> sort-of defeats some of the things that make TypeScript great – namely the type safety. But, if it makes your code easier to test, its probably worth it (in my opinion).