4

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?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Toolmaker
  • 554
  • 6
  • 22

1 Answers1

0

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

lecstor
  • 5,619
  • 21
  • 27
  • These values are constants within the Screeps environment. How else woulx you specify these values apart from being constants in a .d.ts? I will try adding these to the Jest global config and see how that works out, thanks for the tip! – Toolmaker Dec 08 '18 at 17:34
  • I've had a chance to test out your proposed solution and it works! Thank you so much. *tips hat* – Toolmaker Dec 08 '18 at 23:49
  • I was going to say I was unfamiliar with screeps, but I have seen it before.. cool. If you have to have globals as their required by your env, then yeh, there's probably no getting around it. I just meant I'd avoid globals in general and use specific imports for the values I need. Glad the jest globals worked for you! – lecstor Dec 09 '18 at 00:20