I'm attempting to simulate Cloudwatch in AWS using Jest and typescript, but I'm encountering an issue when trying to create a spy for the Cloudwatch.getMetricStatistics() function.
The relevant parts of the app code are as follows:
import AWS, { CloudWatch } from 'aws-sdk';
const cloudWatch = new AWS.CloudWatch();
/* build params */
const metrics = cloudWatch.getMetricStatistics(params).promise();
The test code is outlined below with comments.
const mockGetMetricStatisticsOutput = {
Datapoints: {
reduce: jest.fn().mockImplementation(() => 1),
},
} as unknown as PromiseResult<AWS.CloudWatch.GetMetricStatisticsOutput, AWS.AWSError>;
const getMetricStatisticsSpy = jest.fn().mockReturnValue({
promise: () => new Promise((resolve) => resolve(mockGetMetricStatisticsOutput)),
});
jest.mock('aws-sdk', () => ({
CloudWatch: jest.fn(() => ({
/* THIS WORKS, but I cannot spy on the getMetricsStatistics function so TEST 1 fails */
getMetricStatistics: jest.fn().mockReturnValue({
promise: () => new Promise((resolve) => resolve(mockGetMetricStatisticsOutput)),
}),
/* The following two definitions result in the error shown - even though the spy is defined exactly like that above */
// getMetricStatistics: () => getMetricStatisticsSpy, /* ERROR, Promise not a function */
// getMetricStatistics: () => Promise.resolve(getMetricStatisticsSpy), /* ERROR, Promise not a function */
})),
}));
The issue arises when trying to utilize the getMetricsSpy, which is defined identically to the functioning inline definition within the code. When attempting to use the spy as displayed in the commented out lines, I receive an error in the app code on the mentioned line:
const metrics = cloudWatch.getMetricStatistics(params).promise();
The error states that "promise is not a function." This occurs while running the test.
Any insights into what I might be doing incorrectly here?