Jest/TypeScript – partial type mock

Consider these types:

Let’s say you are testing a component that fires off an API call to retrieve on object that should match IHuman. In your test you will want to create a mock version of this, – usually referred to as stub or a fixture. Let’s look at an example of how that might go:

This will run fine and be completely happy as we have all the correct typing in our mock object. Let’s consider a scenario in which the type is much more complex and we only really care about some of the values for our use case, or in this specific example let’s pretend that we want to check all the stats of a human, but don’t care if they have a pet.

Typescript is going to be angry at us, because pet is not a nullable and it wants to see that type exist. My own personal experience with this was when I was mocking Stripe objects in tests, some of the types were huge and I only wanted to stub the properties I needed, otherwise I would have been down the rabbit hole. Let’s see how we can do this:

These little helpers use generics to allow us to take a type, and enforce type safety only for keys that have been provided, keys that have been provided must match their specification, but if they have not been provided they will be ignored and will not cause an error.