177 Followers
·
Follow

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 Partial as a parameter and returns that partial casted as the desired type.

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

Written by

Software Developer from Omaha, NE.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store