在打字稿中创建间谍时"Promise is not a function"开玩笑错误



我正在尝试使用Jest和typescript在AWS中模拟Cloudwatch。我在为Cloudwatch.getMetricStatistics((函数创建间谍时遇到问题。

应用程序代码执行以下操作(仅显示相关行(:

import AWS, { CloudWatch } from 'aws-sdk';
const cloudWatch = new AWS.CloudWatch();
/* build params */
const metrics = cloudWatch.getMetricStatistics(params).promise();

测试代码使用注释执行以下操作。

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 */
})),
}));

问题是当尝试使用getMetricsSpy时,它被定义为代码的工作内联定义。如果我试图使用注释行中显示的间谍,我会在这行的应用程序代码中得到一个错误:

const metrics = cloudWatch.getMetricStatistics(params).promise();

声明";承诺不是一种功能";。我在运行测试时得到了这个。

你知道我在这里做错了什么吗?

这看起来很奇怪:

CloudWatch: jest.fn(() => ({

根据文件。我很确定你想要:

CloudWatch: () => ({

jest.fn()是一个跟踪它是如何被调用的函数,因此您可以测试调用函数的东西。但是这个api需要一个通用函数。它可能会以某种方式干扰玩笑。

相关内容

最新更新