Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you test a function argument with the wrong type in ts-jest?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How do you test this?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading