Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a test of TypeScript compile error

Tags:

typescript

I'm looking for a possibility how to write a unit test which will test a function if it throws a TypeScript error.

I have this code:

class MyClass {
  method() { }
  property: number = 10;
}

function someFunction<T, M extends keyof T & {
  [Property in keyof T[M]]: Function;
}>(object: T, method: M) {

}

const myClass = new MyClass();

// next row will throw an error because myClass.property isn't a function
someFunction(myClass, "property");

And I need to test if this code throws a TypeScript Error. If it does, than everything is alright.

Why? This code is only a sample. I have a library and my intension is to define what a function should do. I want to provide the function someFunction with these rules. So that means the name of a method will be allways a name of a function, not number or string, etc.

I would like to write a test which will check that I haven't broke this logic in future. I think I can put this simple example to a separated ignored file and write my own testing library which will load the file and run tsc compiler directly. But before I would like to do such thing I would like to ask if is there any tool I can use instead.

like image 842
user1173536 Avatar asked Sep 05 '25 03:09

user1173536


1 Answers

I just added a typescript compile step to my CI tooling to stop me having to run it manually (see https://github.com/cefn/lauf/blob/main/.github/workflows/tests.yml#L29-L30 )

In my repo I have github actions set up to run tsc --noEmit to reveal any compilation errors I may have introduced in a branch before allowing me to merge it. It's not authored as a test suite as such but it operates in exactly the same part of the pipeline.

In your case you want to run this on some sub-folder (let's say ./failures/ but know that the compile FAILED which is to say invert the exit status - if it was non-zero that's good, therefore should resolve to zero. If it was zero that's bad, therefore should resolve to non-zero.

If you're in a bash environment you might achieve this with an extra script target in your package.json then invoke this npm script from whatever build or integration pipeline you are using like npm run verifyfailures

  "scripts": {
    "verifyfailures": "npx --no-install tsc --noEmit ./failures/; if [ $? -eq 0 ] ; then echo 'INCORRECTLY PASSED' && false ; else echo 'CORRECTLY FAILED' && true; fi"
  },
like image 70
cefn Avatar answered Sep 07 '25 19:09

cefn