I am working on a JavaScript project and it has a method including some s3 file reading function as well, and I tried to add some unit test to this method but it didn’t cover the lines. I’ll attach my unit test and code here. Please help me to write unit test for this method.
test('readFileAsJson should return JSON data from S3', async () => {
const mockResponse = { Body: ['{"name": "John"}'] };
s3Service.s3Client.send = jest.fn().mockResolvedValue(mockResponse);
const jsonData = await s3Service.readFileAsJson('test-bucket', 'test-file');
expect(jsonData).toBeDefined();
});
import {
S3Client,
GetObjectCommand,
PutObjectCommand,
} from '@aws-sdk/client-s3';
import {
MAX_ATTEMPTS,
BACK_OFF_RATIO,
INITIAL_DELAY,
REGION,
} from '../../util/constant';
import { awsRetryConfig } from '../../helpers';
class S3Service {
constructor() {
const retryConfigs = awsRetryConfig({
maxAttempts: MAX_ATTEMPTS,
backOffRatio: BACK_OFF_RATIO,
initialDelay: INITIAL_DELAY,
});
this.s3Client = new S3Client({ region: REGION, ...retryConfigs });
}
async readFileAsJson(bucketName, fileKey) {
try {
const command = new GetObjectCommand({
Bucket: bucketName,
Key: fileKey,
});
const response = await this.s3Client.send(command);
let data = '';
for await (const chunk of response.Body) {
data += chunk;
}
const jsonData = JSON.parse(data);
return jsonData;
} catch (error) {
throw new Error(error);
}
}
export default new S3Service();