gpt4 book ai didi

node.js - 如何用 Jest 模拟 s3.upload() - node.js

转载 作者:行者123 更新时间:2023-12-05 08:05:56 24 4
gpt4 key购买 nike

我尝试用 this 模拟 s3 上传功能指令但是当我使用这种模式时有一个

TypeError: s3.upload is not a function

// upload.test.js
const AWS = require('aws-sdk');
jest.mock('aws-sdk', () => {
const mS3 = { upload: jest.fn().mockReturnThis(), promise: jest.fn() };
return { S3: jest.fn(() => mS3) };
});

const s3 = new AWS.S3();
s3.upload({}).promise.mockResolvedValueOnce({ Bucket: 'XXX' });

我也在使用 SQS 并且使用这种模式我有另一个错误:

AWS.SQS is not a constructor

我该如何应对?

// upload.js
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
s3Params = {
Bucket: S3_BUCKET,
Key: `example.xml`,
ACL: 'public-read',
ContentType: 'application/json',
Body: Buffer.from(file)
}
}
await s3.upload(s3Params).promise();

最佳答案

当使用 Jest .mockReturnValueOnce 时,您需要在该值设置为能够接收您在 mockReturnValueOnce 中定义的值作为响应后执行模拟,

例如模拟S3:

// s3-mock.test.js
let AWS = require('aws-sdk');

jest.mock('aws-sdk', () => {
let instance = {
upload: jest.fn().mockReturnThis(),
promise: jest.fn(),
};
return { S3: jest.fn(() => instance) };
});


describe("setup for s3.upload testing", () => {
let testS3;
beforeEach(() => {
testS3 = new AWS.S3();
testS3.promise.mockReturnValueOnce({ Bucket: 'TestBucketName' });
})

test('returns expected upload value', async () => {
let params = {};
let result = await testS3.upload(params).promise();
expect(result).toEqual({ Bucket: 'TestBucketName' });
expect(result.Bucket).toBe("TestBucketName")
});
});

和模拟 SQS:

// sqs-mock.test
let AWS = require('aws-sdk');

jest.mock('aws-sdk', () => {
let instance = {
sendMessage: jest.fn().mockReturnThis(),
promise: jest.fn(),
};
return { SQS: jest.fn(() => instance) };
});


describe("setup for sqs.sendMessage testing", () => {
let testSQS;
beforeEach(() => {
testSQS = new AWS.SQS();
testSQS.promise.mockReturnValueOnce({ MessageId: 'TestSQSId' });
})

test('returns expected message id', async () => {
let params = {};
let result = await testSQS.sendMessage(params).promise();
expect(result).toEqual({ MessageId: 'TestSQSId' });
expect(result.MessageId).toBe("TestSQSId")
});
});

关于 https://github.com/oieduardorabelo/jest-mock-aws-sdk 的工作示例

如您所见,它们是相同的,您还可以在 Jest 中使用手动模拟,文件夹 __mocks__ 包含所有包,并在测试中模拟,请查看以下文档: https://jestjs.io/docs/manual-mocks

关于node.js - 如何用 Jest 模拟 s3.upload() - node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62754417/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com