javascript - 如何在 jest Node JS 中测试 AWS 中使用的 .promise() 方法内置方法
问题描述
我想对此进行完全单元测试,下面给出了我的函数的代码
function.js
async function sesSendEmail(message) {
var ses = new aws.SES({ apiVersion: "2020-12-01" });
var params = {
Source: "abc@gmail.com",
Template: "deviceUsageStatisticsEmailTemplate",
Destination: {
ToAddresses: ["xyz@gmail.com"]
},
TemplateData: message,
}
try {
let res = await ses.sendTemplatedEmail(params).promise()
console.log(res)
}
catch (err) {
console.log(err)
}
到目前为止,我在测试中尝试过的内容:
function.test.js
test('should send templated email success', async () => {
jest.spyOn(console, 'log');
const mData = {};
ses.sendTemplatedEmail.mockImplementationOnce(async (params,callback) => {
callback(null,mData)
});
const message = 'mock message';
await index.sesSendEmail(message);
expect(aws.SES).toBeCalledWith({ apiVersion: '2020-12-01' });
expect(ses.sendTemplatedEmail).toBeCalledWith(
{
Source: 'abc@gmail.com',
Template: 'deviceUsageStatisticsEmailTemplate',
Destination: {
ToAddresses: ['xyz@gmail.com'],
},
TemplateData: message,
},
);
await expect(console.log).toBeCalledWith(mData);
});
test('should handle error', () => {
const arb = "network error"
ses.sendTemplatedEmail = jest.fn().mockImplementation(() => {
throw new Error(arb);
})
const message = 'mock message'
expect(() => { index.sesSendEmail(message) }).toThrow(arb);
});
});
问题:
它给出了一个错误
expect(jest.fn()).toBeCalledWith(...expected)
- Expected
+ Received
- Object {}
+ [TypeError: ses.sendTemplatedEmail(...).promise is not a function],
我已经尝试过模拟实现的变化,但无济于事..任何帮助/建议都非常感谢:)
更新
试过要求aws-sdk-mock
aws.mock('ses','sendTemplatedEmail',function(callback){callback(null,mData)})
但仍然出现错误
TypeError: Cannot stub non-existent own property ses
解决方案
TypeError: ses.sendTemplatedEmail(...).promise is not a function
意味着它期望调用的结果ses.sendTemplatedEmail()
是一个具有名为 的函数属性的对象promise
。
为了解决这个问题,您需要从您的模拟实现中返回一个具有预期promise
属性的对象。您还需要async
从模拟实现中删除关键字,因为这将返回一个 Promise 对象,而不是具有promise
属性的预期对象。
下面是一个示例,它也.promise()
按照生产实现的预期返回一个 Promise 对象sendTemplatedEmail.promise()
:
ses.sendTemplatedEmail.mockImplementationOnce((params,callback) => ({
promise: () => Promise.resolve(callback(null,mData)),
}));
推荐阅读
- reactjs - 将 create-react-app 项目传输到 Webpack 并且没有错误,但永远不会调用 index.js
- swift - UITextField 在不是时被视为 nil
- javascript - 如何在javascript中用数组中的索引替换键
- javascript - 如何识别数组中的最大数字,但如果两个或更多数字被绑定为最大数字,则无法识别?
- python - 熊猫中的自定义 Grouper 对象
- python - 将行分成偶数组并给出新的组名
- java - 有没有办法让IDEA在多行时不对齐方法?
- python - Django 模板在当前 URL 后添加 GET 参数
- karate - 如何在场景大纲中呈现 Karate.Config 值
- ios - 目标c:用另一层遮罩层并改变框架时的奇怪行为