Hacker News new | ask | show | jobs
by venuzr 3665 days ago
Are there any patterns / recommended practices for unit testing Typescript. I recently joined a project which uses Angular1 + Typescript and had to introduce unit testing to the code base and it has been painful. A lot of backend API calls (wrapped in services) are being (chained and) invoked in the constructor. Any initialization is being squashed into the constructor. This makes setup of karma tests extremely painful/brittle without a complete refactor for each component. However wrapping initialization code in public methods feel strange to me. Any suggestions?
2 comments

I don't know exactly what your code looks like, but a major reason for using Dependency Injection, like AngularJS does, is to allow your tests to "mock" the injected services. Then, you verify the behaviour (but not the implementation), by checking that each mock is invoked with the expected arguments, and set it to return a particular value.

On the server side, I've used TypeMoq, which is pretty nice. I have only used it to mock imported modules; for AngularJS 1, you'd need to invoke the "inject" service, to insert your mocks into the controller.

Further reading:

https://en.wikipedia.org/wiki/Mock_object

I have found Angular 1 to be an untestable hot mess, especially on projects with a lot of technical debt. This is largely unrelated to TypeScript (and probably unrelated to Angular 1's shortcomings too).

My only suggestion is start migrating to Angular 2 immediately.