awslabs / aws-embedded-metrics-node

Amazon CloudWatch Embedded Metric Format Client Library
https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html
Apache License 2.0
249 stars 35 forks source link

"no exported member 'mockLogger'" error when mocking the library in TypeScript #139

Open simonespa opened 1 year ago

simonespa commented 1 year ago

Context

I'm using this library to send metrics via the metricScope and I need to test the functionality. To do so I'm following the example described here https://github.com/awslabs/aws-embedded-metrics-node/blob/master/examples/testing/tests/module.jest.test.js.

The project is written in TypeScript and I use jest for unit testing.

Issue

This example https://github.com/awslabs/aws-embedded-metrics-node/blob/master/examples/testing/tests/module.jest.test.js fails in a TypeScript context with the following error:

Module '"aws-embedded-metrics"' has no exported member 'mockLogger'.ts(2305)

Question

simonespa commented 1 year ago

My workaround to make TypeScript happy was to extend the definition of the library by declaring the following:

declare module 'aws-embedded-metrics' {
  const mockLogger: {
    setNamespace: (value: string) => MetricsLogger;
    setDimensions: (dimensionSet: Record<string, string>) => MetricsLogger;
    setProperty: (key: string, value: unknown) => MetricsLogger;
    putMetric: (key: string, value: number, unit?: Unit | string) => MetricsLogger;
  };
}

By doing so I can use the mockLogger object returned by the stubbed library.

simonespa commented 1 year ago

I also tried other approaches to pass the "mockLogger" without being part of the aws-embedded-metrics to avoid any TypeScript complaint. Unfortunately, the fact that Jest hoists the jest.mock definition doesn't help.