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 ?
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.
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.
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) {
}
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With