EmandM / ts-mock-imports

Intuitive mocking library for Typescript class imports
MIT License
109 stars 8 forks source link

Mocking a static class resolves the wrong type #36

Closed RageCage64 closed 3 years ago

RageCage64 commented 3 years ago

Hello! First, thank you for your hard work maintaining this helpful library. It solved a big problem for me.

I am experiencing a bug with ImportMock.mockStaticClass where it appears to be mocking the wrong type and causing a TypeScript error. I am trying to mock a static method on the DynamoDBDocumentClient called from in the package @aws-sdk/lib-dynamodb.

I have an example very similar to the following Gist: https://gist.github.com/BraydonKains/3b8e8fc56ce08b7df17868d18f19da28

This results in a TypeScript error:

Type 'StaticMockManager<BatchExecuteStatementCommand>' is not assignable to type 'StaticMockManager<DynamoDBDocumentClient>'.
  Type 'BatchExecuteStatementCommand' is missing the following properties from type 'DynamoDBDocumentClient': config, destroy, sendts(2322)

As an experiment, I deleted the type in the variable declaration and had the language server infer the type from usage; this resulted in inferring the same unexpected StaticMockManager<DynamoDBLibModule.BatchExecuteStatementCommand>.

I am unsure if this bug is a result of strange declaration on the side of the AWS package or is somehow a bug in this package, but I thought this would be the best place to start.

Thank you in advance!

EmandM commented 3 years ago

This issue occurs when multiple types are being passed out from the same module. Typescript has no clear information to infer types on and so will simply pick the first exported type. To guarantee correct type information, explicitly pass the expected types into the mockStaticClass call.

documentClientImportMock = ImportMock.mockStaticClass<DynamoDBLibModule.DynamoDBDocumentClient>(DynamoDBLibModule, "DynamoDBDocumentClient");