I see the answer here Mocking aws-sdk S3#putObject instance method using jest, but it's not working as-is and it's not explained at all so I don't know what's going on.
I have a function:
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
exports.saveImageToS3 = async (params) => {
try {
const s3resp = await s3.putObject(params).promise();
/* Happy path response looks like this:
data = {
ETag: "\"6805f2cfc46c0f04559748bb039d69ae\"",
VersionId: "psM2sYY4.o1501dSx8wMvnkOzSBB.V4a" // version optional
}*/
if (s3resp.hasOwnProperty('ETag')) { // expected successful response
return { success: true, key: params.Key } // returning key of item if we have reason to think this was successful.
} else {
console.warn("Unexpected s3 response format: ", s3resp)
return s3resp;
}
} catch (err) {
throw err;
}
}
I'd like to test if it works.
I do not understand how to mock the s3.putObject function.
I have tried:
describe('FUNCTION: saveImageToS3', () => {
const mockedPutObject = jest.fn();
jest.mock('aws-sdk', () => {
return class S3 {
putObject(params, cb) {
console.log("Mocked putObject function");
mockedPutObject(params, cb);
}
}
});
test('returns success object with correct key value', async () => {
await expect(await utils.saveImageToS3(params)).toEqual({ success: true, key: `original/testCamId/testCamId___2022-04-06T06-30-59Z.jpg` })
})
})
per the above-linked answer, but the test fails (times out, actually) and the output "Mocked putObject function" never is written to the console, telling me the mocked aws-sdk isn't being used...