2023-03-13
Testing JavaScript Logic Using the AWS SDK v3
Some time ago AWS introduced the version 3 SDK for JavaScript which I have recently employed in a NodeJS project. One would use the SDK roughly in this manner after adding a dependency to @aws-sdk/client-iam
;
...
const iamClient = new IAMClient(awsClientConfig);
const result = iamClient.send(new GetRoleCommand({RoleName: roleName}));
...
Using jest, this structure is tricky to mock in a readable manner. Happily there exists a libary aws-sdk-client-mock
and aws-sdk-client-mock-jest
which can help out with the mocking. This would be used as follows;
// GIVEN
...
const iamClient = mockClient(IAMClient);
iamClient
.on(GetRoleCommand)
.resolves({ RoleName: 'Sebastian' });
// WHEN
// run the logic that uses the AWS SDK v3
// THEN
expect(iamClient).toHaveReceivedCommand(GetRoleCommand);
This has proven to be an easier way to mock the AWS SDK v3 in unit tests.