Writing unit tests for code that interacts with the AWS JavaScript SDK v3 comes with two major benefits. Obviously, writing unit tests ensures you catch bugs early and therefore increase the quality of your code. Also, writing unit tests enables you to run your code locally without the need to reach out to the AWS service APIs. But how do you write unit tests for code interacting with the AWS JavaScript SDK v3?
The following code snippet shows the index.js file containing a handler() function, which could be deployed as a Lambda function. The handler() function lists all buckets belonging to an AWS account.
So, how do I write a unit test? I prefer using the test framework mocha to write JavaScript tests. The following snippet shows the test/test.index.js file containing the skeleton to implement a test.
import { deepStrictEqual } from'node:assert';
import { handler } from'../index.js';
describe('demo', () => { it('handler', async () => { const now = newDate().toISOString(); const result = await handler({}, {}); // Call the handler() function deepStrictEqual(result, [{ // Verify the response Name: 'bucket-demo-1', CreationDate: now }]) }); });
When executing the test, the handler() function will send a request to the S3 API. But doing so is not feasible for unit testing, as it is very challenging to ensure the response matches the assumptions in the unit test.
Instead of sending requests to the AWS APIs use a common testing technique called mocking. A mock simulates a dependency. So let’s mock the AWS Java Script SDK v3 by extending the test/test.index.js file.
exportasyncfunctionhandler(event, context) { let result = ''; const paginator = paginateScan({ // pageinateScan calls ScanCommand multiple times to iterate over all result pages client: dynamodbClient }, { TableName: 'demo' }); forawait (const page of paginator) { result = result + page.Items[0].Data.S; } return result; }
To write a unit test override the underlying command, ScanCommand in this example.
The tricky part when writing mocks for the AWS SDK is to ensure comatiblity with the real-world. That’s why I do not rely on unit testing. On top of that, integration testing against the AWS APIs is necessary.
Summary
aws-sdk-client-mock is a handy tool when it comes to writing unit tests for code that interacts with the AWS JavaScript SDK v3. It has never been easier to write unit tests!