Search code examples
typescriptjestjsscreepsts-jest

ts-jest - declare const from typing (.d.ts) values are undefined when running jest


I'm relatively new to use Typescript and Jest and I've been running into an issue where I have a whole bunch of ambient declarations in a typings files (index.d.ts) in @types/screeps. These look like this:

declare const OK: 0;
declare const ERR_NOT_OWNER: -1;
//etc.

Whenever I use these constants in a test, I will get an ReferenceError: OK is not defined within Jest. If I do declare the value within the test the location of the error will move to the file being tested.

I did some googling around and I found this particular bug in the ts-jest repository: https://github.com/kulshekhar/ts-jest/issues/112

However, I'm having a hard time following the discussion because I hardly ever used Typescript and really do not understand how I can solve this issue myself. What I want is to be able to declare these values in the ambient scope and use them in my tests. Whenever the code is compiled using rollup the type will get picked up(since it's an globally available value in Screeps during runtime and the compiled output is fine). I don't mind tweaking the tsconfig.json or copying files / hacking a solution together.

I tried copying the index.d.ts from the @types folder into my test folder, tried doing an import on it, tried changing the declare const to export const (but then I need to import the module and it's all in a particular namespace). Tried doing a declare global, no luck either.

It seems this behavior is intentional for reasons beyond my comprehension. I'm really confused, is there a way for me to solve this? Or am I just outta luck?


Solution

  • I could be wrong, but it feels like declaring these values as constants in d.ts is maybe not the right way to go, but I could be wrong.

    That being said, have you tried adding them in the jest config globals object?

    https://jestjs.io/docs/en/configuration#globals-object