首页 > 解决方案 > 如何在 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

标签: javascriptnode.jsamazon-web-servicesjestjsasync.js

解决方案


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

推荐阅读