使用Jest模拟同一个AWS Lambda函数中的两个S3 API调用 [英] Mocking two S3 API calls in the same AWS Lambda function using Jest

查看:81
本文介绍了使用Jest模拟同一个AWS Lambda函数中的两个S3 API调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在同一个Lambda函数中模拟两个S3调用,但是似乎遇到访问被拒绝"错误,因此这使我相信S3调用没有被模拟.我目前使用的语法仅在模拟该函数中的一个S3调用时有效,但是我当前正在测试的函数具有两个S3调用(deleteObject和putObject).

I'm trying to mock two S3 calls in the same Lambda function but seem to be getting Access Denied errors so this leads me to believe the S3 calls are not being mocked. The syntax I'm currently using works when mocking just one S3 call in the function but the function I'm currently testing has two S3 calls(deleteObject and putObject).

这是我的模拟代码:

 const putObjectMock = jest.fn(() => ({
      promise: jest.fn(),
 }));

 const deleteObjectMock = jest.fn(() => ({
      promise: jest.fn(),
 })));

 jest.mock("aws-sdk", () => ({
      S3: jest.fn(() => ({
           deleteObject: deleteObjectMock,
           putObject: putObjectMock,
      })),
 }));

我的测试:

 const newHandler = Handler.handler
 const returnValue = await handler ({
      queryStringParameters: {
           eventListValue: "test",
           eventListName: "test2",
      body: {newStuff: "stuff goes here", eventList: [] },
 });
 expect(returnValue).toEqual({
      statusCode:200,
      headers: {
           "Access-Control-Allow-Origin": "*",
           "Access-Control-Allow-Credentials": true,
      },
      body: undefined
 })
 });

文件中具有两个S3调用的部分:

And the part of the file that has the two S3 calls:

 if(event.queryStringParameters.value){
      await s3.deleteObject({Bucket: "my-bucket-name", Key: "name-of-object", 
 }).promise()
 }

 const putObjectResponse = await s3.putObject({Bucket: "my-bucket-name", Key: 
 "name-of-object",
  ContentType: "application/json", Body: event.body}).promise();

尝试对此进行测试时,返回拒绝访问.任何帮助都会很棒.

Access denied is returned when I try to test this. Any help would be great.

推荐答案

问题是因为我使用的是特定的服务导入,而不是代码文件中的顶级导入.

Problem was because I was using the specific service import instead of the top-level import in my code file.

已更改

 const S3 = require("aws-sdk/clients/s3");

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

这篇关于使用Jest模拟同一个AWS Lambda函数中的两个S3 API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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