screepers / Screeps-Typescript-Declarations

The repository for *Screeps's* TypeScript type definitions.
69 stars 44 forks source link

Question - how to make ts-jest happy at test runtime? #132

Closed stkiller closed 3 years ago

stkiller commented 3 years ago

Hello there!

I'm struggling with setting up unit tests that depend on Screeps types.

For example, when trying to extend Creeps like this:

Creep.prototype.someFunction = ...

My IDE is happy, the compiled code runs in game just fine, all types are resolved. But, when executing a unit test that imports the above code, it always fails with

ReferenceError: Creep is not defined

How to teach ts-jest to look at the right place and resolve Creep and other types located in node_modules/@types/screeps/index.d.ts ?

Thank you in advance!

stkiller commented 3 years ago

Below is based on my own understanding, take with a grain of salt.

Anything found in *.d.ts is just a declaration to help your IDE and TypeScript figure out if the code is wrong. None of these types are available at runtime.

With Screeps, where the majority of implementations are provided at runtime, testing is tough-er than usual - you need to mock everything. There are good starting projects, though. https://github.com/eduter/screeps-typescript-jest-starter https://github.com/eduter/screeps-jest

Take a look at https://github.com/eduter/screeps-jest/blob/master/src/setupGlobals.ts#L1601

Specifically, everything added to global before the start of the test will be available at test runtime.

Closing this issue