I am testing a function written in TypeScript. To avoid having to compile my project every time, I am using ts-jest.
There is a caveat, though, that I am not sure there is a workaround for. I've checked the ts-jest options without much luck. The function allows only a string for input.
function tsFunc(arg:string){
if (typeof(arg)!=='string'){
throw new TypeError('....')
}
}
But I can't test it since using tsFunc(5) won't compile in the test files.
How do you test this?
If you specifically want to test arguments that violate the the type contract of the function, then you need to cast that argument to any to basically tell Typescript to disable type checking on that variable.
expect(() => {
tsFunc(123 as any);
}).toThrow();
Or you could add a // @ts-expect-error comment.
expect(() => {
// @ts-expect-error testing wrong argument type
tsFunc(123);
}).toThrow();
Which to use is up to you. But somehow you need to tell Typescript that you are doing something wrong on purpose.
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