Using Partial and Pick for Testing in TypeScript

On my current project, I wanted to write some tests in TypeScript. In these tests, I want to check that some source data was displayed as expected. I ended up finding Partial and Pick Types to be handy. I’ll explain.

For the test, I wanted to set up stub data of a predefined object of one type and then feed it into a component. Next, I wanted to assert that the data resulted in the expected output on the page.

However, while writing the test, I realized the data I needed to provide was stored in a type that held a lot of other, irrelevant information. If I filled in the object entirely, I worried the test would be overly busy and difficult to understand because of this extra noise.

An Example Test

Let’s use the example of Type Dog, where dog contains a color: String, weight: number, createdDate, and updatetDate and Rating: DogRating.  This test will be using dog rating to show data on the page. But this test doesn’t need to use the created or updated date.

Here is the type definition for a Dog:

type Dog = {
  color: string, 
  weight: number,
  createdDate: Date,
  updatetDate: Date, 
  rating: DogRating

I wanted to find a way to cut out that extra information and just have part of the type. I didn’t want to just create a new type. That’s because if the type of the Rating field changed, I wanted that to be reflected in this test.

One solution I came to was to use the Partial Type.

const partialDoge:  Partial = {
    color: "Brown"
    weight: 42
    rating: { goodness: 100, fluff: "12/10" }

The Partial Type lets you define properties that exist in the input type, but no others. Now if the `Rating` type changes, this code will generate a type error.

Another option for using just one property from the Dog Type would be to use the Pick Type.

  const aFieldFromDog: Pick, "Rating"> = {
    Rating: { 
      goodness: 100,
      fluff: "12/10" 

In this example, I’m choosing just the field called `Rating`.

Partial and Pick Types for More Meaningful Tests

I hope the Partial and Pick Types can help you write simpler and more meaningful tests. Let me know if there are other helpful types you often use for testing.

The post Using Partial and Pick for Testing in TypeScript appeared first on Atomic Spin.

Source: Atomic Object

Leave a Reply

Your email address will not be published.