Simple Typescript Stubs

In my previous post, Angular Component Class Tests, I shared why I prefer to write my Angular unit tests exclusively as component class tests. In this post, I want to share a simple function I use to create typed stubs.

In my previous post, you’ll notice I had to cast my dependencies to the Typescript any type in order to inject them into the constructor. Here’s that example again:

Now, I could have easily used the real type of my service dependency and simply stubbed all of its methods. That is easy enough if your dependency only has a few properties. However, if you’re injecting something like Angular’s Router which has many methods and properties that need to be defined, that strategy can get cumbersome quickly. Speaking in pure JavaScript terms, what you really want is just an object that has all of the properties of the TypeScript type you’re trying to mock set to undefined. So, that’s exactly what I did, and here’s the result:

It’s a simple function that takes a generic type as a parameter, casts an empty object to that type, and then iterates through the properties to set them to undefined. This has suited my needs perfectly for stubbing out dependencies in tests, but I also use it when I want to create a test object from an interface and don’t want to have to specify every value of that interface.

Here’s the previous post’s example, with using the stub function instead of casting the dependency to type any.