如何测试Jest Node JS中内置方法的AWS中使用的.promise()方法 [英] How to test .promise() methods used in AWS built in methods in jest Node JS

查看:104
本文介绍了如何测试Jest Node JS中内置方法的AWS中使用的.promise()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对此进行完全的单元测试,下面给出了我的函数的代码

I want to unit test this completely the code for my function is given below

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

到目前为止我在测试中尝试过的内容:

What i have tried in my tests so far:

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],

我尝试过各种实现方式,但无济于事..非常感谢任何帮助/建议:)

I have tried variations in mockimplementations but to no avail.. any help/suggestion is highly appreciated :)

更新

试图使用aws-sdk-mock

aws.mock('ses','sendTemplatedEmail',function(callback){callback(null,mData)})

但仍然出现错误

TypeError: Cannot stub non-existent own property ses

推荐答案

我会说模拟aws sdk本身,并以通常的方式测试您的方法.在aws-sdk-mock( https://www.npmjs.com/package/aws-sdk-mock )

I would say mock the aws sdk itself and test your methods the way you normally do. Once such library is aws-sdk-mock (https://www.npmjs.com/package/aws-sdk-mock)

类似这样的东西

const sinon = require("sinon");
const AWS = require("aws-sdk-mock");

test("should send templated email success", async () => {
  const sendEmailStub = sinon.stub().resolves("resolved");
  AWS.mock("SES", "sendTemplatedEmail", sendEmailStub);
  const response = await sesSendEmail("{\"hi\": \"bye\"}");
  expect(sendEmailStub.calledOnce).toEqual(true);
  expect(sendEmailStub.calledWith(
    {
      "Source": "abc@gmail.com",
      "Template": "deviceUsageStatisticsEmailTemplate",
      "Destination": {
        "ToAddresses": ["xyz@gmail.com"]
      },
      "TemplateData": "{\"hi\": \"bye\"}"
    })).toEqual(true);
    expect(response).toEqual("resolved");
    AWS.restore();
});

test("should send templated email failure", async () => {
  const sendEmailStubError = sinon.stub().rejects("rejected");
  AWS.mock("SES", "sendTemplatedEmail", sendEmailStubError);
  const response = await sesSendEmail("{\"hi\": \"bye\"}");
  expect(sendEmailStubError.calledOnce).toEqual(true);
  expect(sendEmailStubError.calledWith(
    {
      "Source": "abc@gmail.com",
      "Template": "deviceUsageStatisticsEmailTemplate",
      "Destination": {
        "ToAddresses": ["xyz@gmail.com"]
      },
      "TemplateData": "{\"hi\": \"bye\"}"
    })).toEqual(true);
    expect(response.name).toEqual("rejected");
    AWS.restore();
});

请确保从您的原始方法返回了响应和错误.

Make sure from your original method, you are returning response and error.

这篇关于如何测试Jest Node JS中内置方法的AWS中使用的.promise()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆