Applicable when
- You need to cover JavaScript / TypeScript code that uses the AWS-SDK with unit tests.
Non-applicable when
- You want to modify the AWS-SDK behavior in production.
Implementation
When you need to cover JavaScript code which makes use of the AWS-SDK via regular ECMAScript imports or 'require' statements you may be tempted to mock the library yourself. However, this will prove to be cumbersome since you will most likely need several mocks even if your code only uses a specific method. Given the complexity of the SDK, It is far more convenient to use a library that has the built-in capability of mocking any SDK property. This is why we would recommend using a library such as aws-sdk-mock which you can incorporate into your develop dependencies in your JavaScript / TypeScript project.
Let us illustrate how you can mock and assert logic by looking at the following example of a Lambda function which makes use of S3.getObject:
import { S3 } from 'aws-sdk';
export async function handler(event: any, context: any, callback: any): Promise<void> {
const s3 = new S3();
const readParams = {
Bucket: 'bucket',
Key: 'objectKey'
};
const data = await s3.getObject(readParams).promise();
callback(null, data.Body);
}
import * as AWS from 'aws-sdk';
import * as AWSMock from 'aws-sdk-mock';
import { GetObjectOutput, GetObjectRequest } from 'aws-sdk/clients/s3';
import {} from 'jasmine';
import { spy } from 'sinon';
import { handler } from './sample-lambda';
describe('Sample Lambda', () => {
beforeAll(() => {
AWSMock.setSDKInstance(AWS);
});
afterAll(() => {
AWSMock.restore('S3');
});
it('should get object body', async() => {
// Arrange
const bodyObject = {
Body: 'Object body'
};
const getObjectFn = (
params: GetObjectRequest,
callback: (err: null, data: GetObjectOutput) => void) => {
callback(null, bodyObject);
};
const getObjectSpy = spy(getObjectFn);
AWSMock.mock('S3', 'getObject', getObjectSpy);
// Act
await handler(null, null, jasmine.createSpy());
// Assert
expect(getObjectSpy.getCall(0).args[0]).toEqual({
Bucket: 'bucket',
Key: 'objectKey',
});
});
});
Comments
0 comments
Please sign in to leave a comment.