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
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