Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using partial shape for unit testing with typescript

Let's say i want to unit test a function in typescript. This function use an "option" type (object) parameter with a complex shape.

interface option {
  param1 : string
  param2 : number
  param3 : { 
    param4 : string
    param5 : boolean
    }
  .
  .
  .
  param15 : string
}

const functionToTest = (opt:option)=>{
   ...do stuff with option
}

Now let say i want to write a unit test that mimic the correct behaviour of functionToTest when param1 change, ignoring the other parameter that have no influence on the result.

It's my understanding that to make my test more resilient, i can just write in plain JS

const option1 = {
  param1 : "foo"
}

and do my testing

expect(functionToTest(option1)).to.be.true;

However, if i write my test with typescript, i will have to write a full option1 object with all of the interface (dummy) members, althought most will be ignored, and it will divert the reader from the true goal of the test.

Are there workarounds around this or something i should change in my thinking ?

like image 865
Vincent J Avatar asked May 20 '16 20:05

Vincent J


People also ask

How do you use partial in TypeScript?

Partial Type in TypeScript In TypeScript, we can define a type as optional with a ? question mark. For example, in the below code, lastName is optional. Therefore, even though firstUser has the type User, we can leave out lastName as it is not required.

Should unit tests be written in TypeScript?

There are many advantages to writing your unit tests in TypeScript. For one, you can develop your application using the Test-Driven Development (TDD) paradigm. Statistics for successful software development projects are in favor of TDD.


2 Answers

You can take advantage of typescript's Partial for this.

interface YourInterface {
  prop: string;
  foo: number;
}

const data: Partial<YourInterface> = {   
   prop: 'value'
};

// service is an instance of SomeService
service.sendData(<YourInterface> data);

class SomeService {
  sendData(data: YourInterface) {

  }
}

like image 119
Rui Marques Avatar answered Oct 18 '22 03:10

Rui Marques


In my tests, I use the as type assertion to pass in partial objects to a function.

const options = {
   param1: 'param1',
   param2: 22 
} as Option;

expect(functionToTest(options)).to.be.true;
like image 33
Kristian Roebuck Avatar answered Oct 18 '22 03:10

Kristian Roebuck