Security News
Input Validation Vulnerabilities Dominate MITRE's 2024 CWE Top 25 List
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
aws-sdk-client-mock
Advanced tools
The aws-sdk-client-mock package is a mocking library for AWS SDK v3 clients. It allows developers to mock AWS SDK v3 client methods for unit testing purposes, making it easier to test code that interacts with AWS services without making actual calls to AWS.
Mocking AWS SDK v3 Client Methods
This feature allows you to mock methods of AWS SDK v3 clients. In the example, the S3Client's GetObjectCommand is mocked to return 'mocked data' instead of making an actual call to AWS S3.
const { mockClient } = require('aws-sdk-client-mock');
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
const s3Mock = mockClient(S3Client);
s3Mock.on(GetObjectCommand).resolves({ Body: 'mocked data' });
async function getObject() {
const client = new S3Client();
const command = new GetObjectCommand({ Bucket: 'example-bucket', Key: 'example-key' });
const response = await client.send(command);
return response.Body;
}
getObject().then(data => console.log(data));
Resetting Mocks
This feature allows you to reset the mocks, which is useful for cleaning up between tests. In the example, the mock for GetObjectCommand is reset, so any subsequent calls will not use the mock.
const { mockClient } = require('aws-sdk-client-mock');
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
const s3Mock = mockClient(S3Client);
s3Mock.on(GetObjectCommand).resolves({ Body: 'mocked data' });
// Reset the mock
s3Mock.reset();
async function getObject() {
const client = new S3Client();
const command = new GetObjectCommand({ Bucket: 'example-bucket', Key: 'example-key' });
try {
const response = await client.send(command);
return response.Body;
} catch (error) {
console.error('Error:', error);
}
}
getObject();
Mocking Multiple Commands
This feature allows you to mock multiple commands for a single AWS SDK v3 client. In the example, both GetObjectCommand and PutObjectCommand are mocked with different responses.
const { mockClient } = require('aws-sdk-client-mock');
const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
const s3Mock = mockClient(S3Client);
s3Mock.on(GetObjectCommand).resolves({ Body: 'mocked get data' });
s3Mock.on(PutObjectCommand).resolves({ ETag: 'mocked-etag' });
async function performS3Operations() {
const client = new S3Client();
const getObjectCommand = new GetObjectCommand({ Bucket: 'example-bucket', Key: 'example-key' });
const putObjectCommand = new PutObjectCommand({ Bucket: 'example-bucket', Key: 'example-key', Body: 'data' });
const getObjectResponse = await client.send(getObjectCommand);
const putObjectResponse = await client.send(putObjectCommand);
return { getObjectResponse, putObjectResponse };
}
performS3Operations().then(data => console.log(data));
aws-sdk-mock is a popular library for mocking AWS SDK v2 methods. It provides similar functionality to aws-sdk-client-mock but is designed for AWS SDK v2. It allows developers to mock AWS service methods for unit testing purposes.
mock-aws-s3 is another library for mocking AWS S3 methods. It is designed to work with AWS SDK v2 and provides a way to mock S3 interactions for testing purposes. It is similar to aws-sdk-client-mock but focused solely on S3.
Library recommended by the AWS SDK for JavaScript team - see the introductory post on the AWS blog.
Features:
In action:
The AWS SDK for JavaScript version 3, is the new version of SDK to use in Node.js and browser. It comes with modular architecture and improved typing, thanks to being written in TypeScript.
The recommended way of using it is to create a Client
and use it to send Commands
.
For example, using SNS Client to publish a message to a topic looks like that:
import {PublishCommand, SNSClient} from '@aws-sdk/client-sns';
const sns = new SNSClient({});
const result = await sns.send(new PublishCommand({
TopicArn: 'arn:aws:sns:us-east-1:111111111111:MyTopic',
Message: 'My message',
}));
console.log(`Message published, id: ${result.MessageId}`);
This library provides an easy way to mock sending Commands
and define returned results depending on the Command
type and payload.
npm install -D aws-sdk-client-mock
Warning
If you are getting type errorsArgument of type 'typeof SomeClient' is not assignable to parameter of type...
see instructions here.
@aws-sdk/* | aws-sdk-client-mock |
---|---|
≥ 3.363.0 | ≥ 3.x |
< 3.363.0 | 2.x |
CommonJS:
const {mockClient} = require('aws-sdk-client-mock');
TypeScript / ES6:
import {mockClient} from 'aws-sdk-client-mock';
Create mock for all instances or for given instance of the AWS SDK Client:
const snsMock = mockClient(SNSClient);
const dynamoDB = new DynamoDBClient({});
const dynamoDBMock = mockClient(dynamoDB);
By default, mocked Client#send()
method returns undefined
.
Using the obtained mock instance, you can specify the mock behavior on receiving various commands to send.
See the AwsStub API Reference for all available methods or check out the examples below.
Specify default mock behavior:
snsMock.onAnyCommand().resolves({});
// same as:
snsMock.resolves({});
Specify mock behavior on receiving given command only:
snsMock
.on(PublishCommand)
.resolves({
MessageId: '12345678-1111-2222-3333-111122223333',
});
Specify mock behavior on receiving given command with given payload only:
snsMock
.on(PublishCommand, {
TopicArn: 'arn:aws:sns:us-east-1:111111111111:MyTopic',
Message: 'My message',
})
.resolves({
MessageId: '12345678-4444-5555-6666-111122223333',
});
Not all payload parameters must be defined to match
(you can force strict matching by passing third param strict: true
):
snsMock
.on(PublishCommand, {
Message: 'My message',
})
.resolves({
MessageId: '12345678-4444-5555-6666-111122223333',
});
Specify mock behavior on receiving given payload only:
snsMock
.onAnyCommand({
TopicArn: 'arn:aws:sns:us-east-1:111111111111:MyTopic',
Message: 'My message',
})
.resolves({
MessageId: '12345678-4444-5555-6666-111122223333',
});
Multiple behaviors (for different commands and payloads) may be specified for a single mock:
snsMock
.resolves({ // default for any command
MessageId: '12345678-1111-2222-3333-111122223333'
})
.on(PublishCommand)
.resolves({ // default for PublishCommand
MessageId: '12345678-4444-5555-6666-111122223333'
})
.on(PublishCommand, {
TopicArn: 'arn:aws:sns:us-east-1:111111111111:MyTopic',
Message: 'My message',
})
.resolves({ // for PublishCommand with given input
MessageId: '12345678-7777-8888-9999-111122223333',
});
Specify chained behaviors - next behaviors for consecutive calls:
snsMock
.on(PublishCommand)
.resolvesOnce({ // for the first command call
MessageId: '12345678-1111-1111-1111-111122223333'
})
.resolvesOnce({ // for the second command call
MessageId: '12345678-2222-2222-2222-111122223333'
})
.resolves({ // for further calls
MessageId: '12345678-3333-3333-3333-111122223333'
});
Specify mock throwing an error:
snsMock
.rejects('mocked rejection');
const throttlingError = new Error('mocked rejection');
throttlingError.name = 'ThrottlingException';
snsMock
.rejects(throttlingError);
In rejects()
, you can pass a string, an Error
instance,
or an object with properties.
In each case, it will be converted to an Error
instance.
Specify custom mock function:
snsMock
.callsFake(input => {
if (input.Message === 'My message') {
return {MessageId: '12345678-1111-2222-3333-111122223333'};
} else {
throw new Error('mocked rejection');
}
});
Specify custom mock function for a specific command (chained behavior):
snsMock
.on(PublishCommand)
.callsFake(input => {
if (input.Message === 'My message') {
return {MessageId: '12345678-1111-2222-3333-111122223333'};
} else {
throw new Error('mocked rejection');
}
});
Specify result based on Client configuration, i.e. region:
snsMock
.on(PublishCommand)
.callsFake(async (input, getClient) => {
const client = getClient();
const region = await client.config.region();
return {MessageId: region.substring(0, 2)};
});
Together with resolvesOnce()
, you can also use rejectsOnce()
and callsFakeOnce()
to specify consecutive behaviors.
You can mock the DynamoDBDocumentClient
just like any other Client:
import {DynamoDBClient} from '@aws-sdk/client-dynamodb';
import {DynamoDBDocumentClient, QueryCommand} from '@aws-sdk/lib-dynamodb';
const ddbMock = mockClient(DynamoDBDocumentClient);
ddbMock.on(QueryCommand).resolves({
Items: [{pk: 'a', sk: 'b'}],
});
const dynamodb = new DynamoDBClient({});
const ddb = DynamoDBDocumentClient.from(dynamodb);
const query = await ddb.send(new QueryCommand({
TableName: 'mock',
}));
To mock @aws-sdk/lib-storage
Upload
you need to mock all commands
used under the hood:
import {S3Client, CreateMultipartUploadCommand, UploadPartCommand} from '@aws-sdk/client-s3';
import {Upload} from "@aws-sdk/lib-storage";
const s3Mock = mockClient(S3Client);
// for big files upload:
s3Mock.on(CreateMultipartUploadCommand).resolves({UploadId: '1'});
s3Mock.on(UploadPartCommand).resolves({ETag: '1'});
// for small files upload:
s3ClientMock.on(PutObjectCommand).callsFake(async (input, getClient) => {
getClient().config.endpoint = () => ({hostname: ""}) as any;
return {};
});
const s3Upload = new Upload({
client: new S3Client({}),
params: {
Bucket: 'mock',
Key: 'test',
Body: 'x'.repeat(6 * 1024 * 1024), // 6 MB
},
});
s3Upload.on('httpUploadProgress', (progress) => {
console.log(progress);
});
await s3Upload.done();
This way, the Upload#done()
will complete successfuly.
To cause a failure, you need to specify the rejects()
behavior
for one of the AWS SDK Commands used by the @aws-sdk/lib-storage
.
For uploading a small file (under the defined multipart upload single part size),
lib-storage
sends a PutObjectCommand
. To make it fail:
s3Mock.on(PutObjectCommand).rejects();
For bigger files, it makes a series of calls including CreateMultipartUploadCommand
,
UploadPartCommand
, and CompleteMultipartUploadCommand
. Making any of them fail will fail the upload:
s3Mock.on(UploadPartCommand).rejects();
AWS SDK wraps the stream in the S3 GetObjectCommand
result to provide utility methods to parse it.
To mock it, you need to install the @smithy/util-stream
package
and call the wrapping function sdkStreamMixin()
on the stream you provide as the command output:
import {GetObjectCommand, S3Client} from '@aws-sdk/client-s3';
import {sdkStreamMixin} from '@smithy/util-stream';
import {mockClient} from 'aws-sdk-client-mock';
import {Readable} from 'stream';
import {createReadStream} from 'fs';
const s3Mock = mockClient(S3Client);
it('mocks get object', async () => {
// create Stream from string
const stream = new Readable();
stream.push('hello world');
stream.push(null); // end of stream
// alternatively: create Stream from file
// const stream = createReadStream('./test/data.txt');
// wrap the Stream with SDK mixin
const sdkStream = sdkStreamMixin(stream);
s3Mock.on(GetObjectCommand).resolves({Body: sdkStream});
const s3 = new S3Client({});
const getObjectResult = await s3.send(new GetObjectCommand({Bucket: '', Key: ''}));
const str = await getObjectResult.Body?.transformToString();
expect(str).toBe('hello world');
});
To mock a paginated operation results, simply mock the corresponding Command:
import {DynamoDBClient, paginateQuery, QueryCommand} from '@aws-sdk/client-dynamodb';
import {marshall} from '@aws-sdk/util-dynamodb';
const dynamodbMock = mockClient(DynamoDBClient);
dynamodbMock.on(QueryCommand).resolves({
Items: [
marshall({pk: 'a', sk: 'b'}),
marshall({pk: 'c', sk: 'd'}),
],
});
const dynamodb = new DynamoDBClient({});
const paginator = paginateQuery({client: dynamodb}, {TableName: 'mock'});
const items = [];
for await (const page of paginator) {
items.push(...page.Items || []);
}
The AWS SDK v3 gives an option to use it similarly to v2 SDK,
with command method call instead of send()
:
import {SNS} from '@aws-sdk/client-sns';
const sns = new SNS({});
const result = await sns.publish({
TopicArn: 'arn:aws:sns:us-east-1:111111111111:MyTopic',
Message: 'My message',
});
Although this approach is not recommended by AWS, those calls can be mocked in the standard way:
import {PublishCommand, SNSClient} from '@aws-sdk/client-sns';
const snsMock = mockClient(SNSClient);
snsMock
.on(PublishCommand)
.resolves({
MessageId: '12345678-1111-2222-3333-111122223333',
});
Notice that in mocks you still need to use SNSClient
, not SNS
,
as well as Command
classes.
Inspect received calls:
snsMock.calls(); // all received calls
snsMock.call(0); // first received call
Get calls of a specified command:
snsMock.commandCalls(PublishCommand)
Get calls of a specified command with given payload
(you can force strict matching by passing third param strict: true
):
snsMock.commandCalls(PublishCommand, {Message: 'My message'})
Under the hood, the library uses Sinon.js stub
.
You can get the stub instance to configure and use it directly:
const snsSendStub = snsMock.send;
The Client mock exposes three Sinon.js stub
methods:
reset()
, resetHistory()
, and restore()
.
The reset()
method resets the mock state and behavior.
The Client will continue to be mocked, only now with a clean mock instance,
without any behavior (set with methods like on(...).resolves(...)
) and calls history.
You should call clientMock.reset()
before or after every test
(using beforeEach()
/ beforeAll()
from your test framework)
to keep tests independent from each other.
The resetHistory()
only clear mocked client calls history
that you access with mockedClient.call(...)
and mockedClient.calls()
.
The behavior is preserved.
The restore()
removes the mock altogether,
restoring the normal behavior of client.send()
.
You can also pass custom Sinon Sandbox
with mockClient(client, { sandbox: mySandbox })
to manage all mocks lifecycle at once.
Custom Jest matchers simplify verification that the mocked Client was called with given Commands.
Matchers are published as a separate package. Install it:
npm install -D aws-sdk-client-mock-jest
Usage (notice the import
):
import 'aws-sdk-client-mock-jest';
// a PublishCommand was sent to SNS
expect(snsMock).toHaveReceivedCommand(PublishCommand);
// at least one command was sent to SNS
expect(snsMock).toHaveReceivedAnyCommand();
// two PublishCommands were sent to SNS
expect(snsMock).toHaveReceivedCommandTimes(PublishCommand, 2);
// a PublishCommand with Message "hello world" was sent to SNS
expect(snsMock).toHaveReceivedCommandWith(
PublishCommand, {Message: 'hello world'}
);
// a PublishCommand with Message containing "hello" was sent to SNS
expect(snsMock).toHaveReceivedCommandWith(
PublishCommand, {Message: expect.stringContaining('hello')}
);
// the second command sent to SNS was a PublishCommand with Message "hello world"
expect(snsMock).toHaveReceivedNthCommandWith(
2, PublishCommand, {Message: 'hello world'}
);
// the second PublishCommand sent to SNS had Message "hello world"
expect(snsMock).toHaveReceivedNthSpecificCommandWith(
2, PublishCommand, {Message: 'hello world'}
);
Shorter aliases exist, like toReceiveCommandTimes()
.
Use those matchers with Vitest:
import 'aws-sdk-client-mock-jest/vitest';
import { expect } from 'vitest';
// a PublishCommand was sent to SNS
expect(snsMock).toHaveReceivedCommand(PublishCommand);
To use the matchers outside of Jest, you can pull in the expect library separately and add it to the global scope directly, e.g.:
const {expect} = require("expect");
(globalThis as any).expect = expect;
require("aws-sdk-client-mock-jest");
See the full API Reference.
Example below uses Jest as a test framework, but mocks will work with any testing library.
Let's take a simple Lambda function that takes a list of messages, sends them to SNS topic and returns message IDs:
import {PublishCommand, SNSClient} from '@aws-sdk/client-sns';
const snsTopicArn = process.env.SNS_TOPIC_ARN || '';
const sns = new SNSClient({});
export const handler = async (event: Event): Promise<string[]> => {
const promises = event.messages.map(async (msg, idx) => {
const publish = await sns.send(new PublishCommand({
TopicArn: snsTopicArn,
Message: msg,
}));
return publish.MessageId!;
});
return await Promise.all(promises);
};
interface Event {
messages: string[];
}
Then the tests could look like this:
import {mockClient} from 'aws-sdk-client-mock';
import {PublishCommand, SNSClient} from '@aws-sdk/client-sns';
import {handler} from '../src';
const snsMock = mockClient(SNSClient);
/**
* To be sure that unit tests are independent from each other,
* reset mock behavior between the tests.
*/
beforeEach(() => {
snsMock.reset();
});
it('message IDs are returned', async () => {
snsMock.on(PublishCommand).resolves({
MessageId: '12345678-1111-2222-3333-111122223333',
});
const result = await handler({
messages: ['one', 'two', 'three']
});
expect(result).toHaveLength(3);
expect(result[0]).toBe('12345678-1111-2222-3333-111122223333');
});
it('SNS Client is called with PublishCommand', async () => {
snsMock.on(PublishCommand).resolves({
MessageId: '111-222-333',
});
await handler({
messages: ['qq', 'xx']
});
expect(snsMock).toHaveReceivedCommandTimes(PublishCommand, 2);
});
For more examples, see the unit tests.
Note
Those instructions refer to@smithy/types
used by AWS SDK v3.363.0 and above. For version below 3.363.0, perform the same steps for the@aws-sdk/types
package.
If you have multiple versions of @smithy/types
installed in your project,
you can get type errors similar to this:
TS2345: Argument of type 'typeof DynamoDBDocumentClient' is not assignable to parameter of type 'InstanceOrClassType<Client<ServiceInputTypes, MetadataBearer, any>>'.
Type 'typeof DynamoDBDocumentClient' is not assignable to type 'ClassType<Client<ServiceInputTypes, MetadataBearer, any>>'.
The types of 'prototype.middlewareStack.concat' are incompatible between these types.
Type '<InputType extends ServiceInputTypes, OutputType extends ServiceOutputTypes>(from: MiddlewareStack<InputType, OutputType>) => MiddlewareStack<...>' is not assignable to type '<InputType extends ServiceInputTypes, OutputType extends MetadataBearer>(from: MiddlewareStack<InputType, OutputType>) => MiddlewareStack<InputType, OutputType>'.
Types of parameters 'from' and 'from' are incompatible.
Property 'identify' is missing in type 'MiddlewareStack<InputType, OutputType>' but required in type 'MiddlewareStack<InputType, ServiceOutputTypes>'.
Run npm ls @smithy/types
/ pnpm why @smithy/types
/ yarn why @smithy/types
and check if you have more than one version of the package installed.
To solve this, go through the steps until one works:
@aws-sdk/*
packages point to the same version,@aws-sdk/*
packages from package.json
, run npm install
/ pnpm install
/ yarn install
,
restore @aws-sdk/*
packages in package.json
, and run install again,@smithy/types
to your dev dependencies in the latest version,@smithy/types
version with npm overrides,
pnpm overrides, or yarn resolutions,npm ls @smithy/types
/ pnpm why @smithy/types
/ yarn why @smithy/types
.If you need to explicitly type the mock variable,
you can use AwsClientStub
type:
import {AwsClientStub, mockClient} from 'aws-sdk-client-mock'
import {S3Client} from "@aws-sdk/client-s3";
const mock: AwsClientStub<S3Client> = mockClient(S3Client);
The AwsClientStub
type works only with tsconfig
option
strictFunctionTypes=true
or (strict=true
) in tsconfig.json
file.
See details in #167.
Wider Command matchers must be declared first, otherwise, they will take precedence over previous ones.
In this case, all PublishCommand
sends will return message ID 222
:
snsMock
.on(PublishCommand, myInput).resolves({MessageId: '111'})
.on(PublishCommand).resolves({MessageId: '222'});
If the order of the declarations is switched, sends with input matching myInput
will return ID 111
and all others 222
.
It works similarly with onAnyCommand()
.
When you create both a Client type mock and a specific Client instance mock(s), you need to declare type mock last. Otherwise, the other instances will not be mocked.
Right now if you create a mock for the Client type, and then mock a specific instance of this Client, with the order of mocking as here:
const sns1 = new SNSClient({}); // not mocked
mockClient(SNSClient).resolves({MessageId: '123'});
const sns2 = new SNSClient({}); // mocked
mockClient(sns2).resolves({MessageId: '456'});
const sns3 = new SNSClient({}); // not mocked
Declaring mocks in this order will fix it:
const sns1 = new SNSClient({}); // mocked - default
const sns2 = new SNSClient({}); // mocked
mockClient(sns2).resolves({MessageId: '456'});
mockClient(SNSClient).resolves({MessageId: '123'});
const sns3 = new SNSClient({}); // mocked - default
PRs to fix this are welcome.
When testing with Mocha, call mockClient()
in the beforeEach()
method, not in the global scope,
to prevent overriding the mock between test files.
See this
for more details.
FAQs
Easy and powerful mocking of AWS SDK v3 Clients
The npm package aws-sdk-client-mock receives a total of 808,750 weekly downloads. As such, aws-sdk-client-mock popularity was classified as popular.
We found that aws-sdk-client-mock demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.