### Install aws-sdk-client-mock Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/README.md Installs the aws-sdk-client-mock package as a development dependency. ```bash npm install -D aws-sdk-client-mock ``` -------------------------------- ### Install aws-sdk-client-mock Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/index.html Installs the aws-sdk-client-mock package as a development dependency using npm. ```bash npm install -D aws-sdk-client-mock ``` -------------------------------- ### Global Expect Setup for Vitest Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/README.md Provides instructions on how to set up the 'expect' library globally for use with Vitest when not using the default Vitest setup. ```javascript const {expect} = require("expect"); (globalThis as any).expect = expect; require("aws-sdk-client-mock-jest"); ``` -------------------------------- ### Install Jest Matchers Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/README.md Installs custom Jest matchers for simplifying verification of mocked Client calls. ```bash npm install -D aws-sdk-client-mock-jest ``` -------------------------------- ### SNS Client Example Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/index.html Demonstrates how to use the AWS SDK v3 SNS Client to publish a message. This example shows the typical usage pattern before mocking. ```typescript 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}`); ``` -------------------------------- ### AWS SDK v3 SNS Publish Example Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/README.md Demonstrates sending a message to an SNS topic using the AWS SDK v3 SNSClient and PublishCommand. ```typescript 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}`); ``` -------------------------------- ### Mocking SDK v2-style SNS PublishCommand Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/README.md Demonstrates how to mock AWS SDK v3 clients when used in an SDK v2-style, where methods like `sns.publish()` are called directly instead of `sns.send(new PublishCommand())`. The mock setup still requires using the `SNSClient` and `PublishCommand` classes. ```typescript import {PublishCommand, SNSClient} from '@aws-sdk/client-sns'; import {mockClient} from 'aws-sdk-client-mock'; const snsMock = mockClient(SNSClient); snsMock .on(PublishCommand) .resolves({ MessageId: '12345678-1111-2222-3333-111122223333', }); // Example of SDK v2-style usage (not mocked directly): // 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', // }); ``` -------------------------------- ### Mocking S3 GetObjectCommand with Streams Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/README.md Shows how to mock the `GetObjectCommand` from `@aws-sdk/client-s3` when the response body is a stream. It requires installing `@smithy/util-stream` and using `sdkStreamMixin()` to wrap the stream before passing it as the command's `Body` output. Includes an example of transforming the stream to a string. ```typescript 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'; const s3Mock = mockClient(S3Client); // create Stream from string const stream = new Readable(); stream.push('hello world'); stream.push(null); // end of stream // 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'); ``` -------------------------------- ### Mocking S3 GetObjectCommand with Streams Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/index.html Explains how to mock the S3 GetObjectCommand, which returns a stream. It requires installing '@smithy/util-stream' and using sdkStreamMixin() to wrap the stream provided as the command output. This allows for testing stream parsing utilities. ```javascript 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'; // Uncomment for file stream 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'); }); ``` -------------------------------- ### Mocking Paginated Operations Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/index.html Shows how to mock paginated operations by mocking the corresponding Command. The example uses DynamoDB's paginateQuery and QueryCommand, demonstrating how to resolve with mocked items and iterate through the paginator using async iterators. ```javascript import {DynamoDBClient, paginateQuery, QueryCommand} from '@aws-sdk/client-dynamodb'; import {marshall} from '@aws-sdk/util-dynamodb'; import {mockClient} from 'aws-sdk-client-mock'; 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 || []); } ``` -------------------------------- ### Mocking Paginated Operations with DynamoDB Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/README.md Illustrates how to mock paginated operations, such as DynamoDB's `paginateQuery`, by mocking the underlying `QueryCommand`. The example shows how to provide mock `Items` and then iterate through the paginated results using an async iterator. ```typescript import {DynamoDBClient, paginateQuery, QueryCommand} from '@aws-sdk/client-dynamodb'; import {marshall} from '@aws-sdk/util-dynamodb'; import {mockClient} from 'aws-sdk-client-mock'; const dynamodbMock = mockClient(DynamoDBClient); dynamodbMock.on(QueryCommand).resolves({ Items: [ marshall({pk: 'a', sk: 'b'}) ], }); const dynamodb = new DynamoDBClient({}); const paginator = paginateQuery({client: dynamodb}, {TableName: 'mock'}); const items = []; for await (const page of paginator) { items.push(...page.Items || []); } ``` -------------------------------- ### AWS Lambda Function with SNS Publish Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/index.html A TypeScript example of an AWS Lambda function that sends messages to an SNS topic using the AWS SDK v3 SNS client. It maps messages to SNS publish operations and returns the MessageIds. ```typescript 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 => { 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[]; } ``` -------------------------------- ### API Reference for aws-sdk-client-mock Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/index.html Links to the comprehensive API reference for aws-sdk-client-mock, hosted on GitHub Pages, providing detailed information on all available methods and functionalities. ```APIDOC API Reference: https://m-radzikowski.github.io/aws-sdk-client-mock/ ``` -------------------------------- ### Theme Initialization Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/hierarchy.html Initializes the theme for the document based on local storage or OS preference. It also sets a timeout to display the application or remove the display none property from the body. ```javascript document.documentElement.dataset.theme = localStorage.getItem("tsd-theme") || "os"; document.body.style.display="none"; setTimeout(() => app?app.showPage():document.body.style.removeProperty("display"),500) ``` -------------------------------- ### AwsStub Class API Documentation Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/classes/AwsStub.html Provides detailed API documentation for the AwsStub class, including its constructor, properties, and methods. This documentation outlines how to use AwsStub to mock AWS SDK v3 client behavior. ```APIDOC Class AwsStub Wrapper on the mocked `Client#send()` method, allowing to configure its behavior. Without any configuration, `Client#send()` invocation returns `undefined`. To define resulting variable type easily, use [AwsClientStub](../types/AwsClientStub.html). Type Parameters: * TInput extends object * TOutput extends MetadataBearer * TConfiguration Implements: * [Behavior](../interfaces/Behavior.html)<[TInput](AwsStub.html#constructor.new_AwsStub.TInput-1), [TOutput](AwsStub.html#constructor.new_AwsStub.TOutput-1), [TOutput](AwsStub.html#constructor.new_AwsStub.TOutput-1), [TConfiguration](AwsStub.html#constructor.new_AwsStub.TConfiguration-1)> Defined in packages/aws-sdk-client-mock/src/awsClientStub.ts:51 Index: Constructors [constructor](AwsStub.html#constructor) Properties [send](AwsStub.html#send) Methods [call](AwsStub.html#call) [calls](AwsStub.html#calls) [callsFake](AwsStub.html#callsFake) [callsFakeOnce](AwsStub.html#callsFakeOnce) [clientName](AwsStub.html#clientName) [commandCall](AwsStub.html#commandCall) [commandCalls](AwsStub.html#commandCalls) [on](AwsStub.html#on) [onAnyCommand](AwsStub.html#onAnyCommand) [rejects](AwsStub.html#rejects) [rejectsOnce](AwsStub.html#rejectsOnce) [reset](AwsStub.html#reset) [resetHistory](AwsStub.html#resetHistory) [resolves](AwsStub.html#resolves) [resolvesOnce](AwsStub.html#resolvesOnce) [restore](AwsStub.html#restore) Constructors ------------ ### constructor[](#constructor) * new AwsStub<[TInput](AwsStub.html#constructor.new_AwsStub.TInput-1), [TOutput](AwsStub.html#constructor.new_AwsStub.TOutput-1), [TConfiguration](AwsStub.html#constructor.new_AwsStub.TConfiguration-1)>(client, send): [AwsStub](AwsStub.html)<[TInput](AwsStub.html#constructor.new_AwsStub.TInput-1), [TOutput](AwsStub.html#constructor.new_AwsStub.TOutput-1), [TConfiguration](AwsStub.html#constructor.new_AwsStub.TConfiguration-1)>[](#constructor.new_AwsStub) * Type Parameters: * TInput extends object * TOutput extends MetadataBearer * TConfiguration * Parameters: * client: Client<[TInput](AwsStub.html#constructor.new_AwsStub.TInput-1), [TOutput](AwsStub.html#constructor.new_AwsStub.TOutput-1), [TConfiguration](AwsStub.html#constructor.new_AwsStub.TConfiguration-1)> * send: SinonStub<[[AwsCommand](../types/AwsCommand.html)<[TInput](AwsStub.html#constructor.new_AwsStub.TInput-1), [TOutput](AwsStub.html#constructor.new_AwsStub.TOutput-1), any, any>], Promise<[TOutput](AwsStub.html#constructor.new_AwsStub.TOutput-1)>> * Returns [AwsStub](AwsStub.html)<[TInput](AwsStub.html#constructor.new_AwsStub.TInput-1), [TOutput](AwsStub.html#constructor.new_AwsStub.TOutput-1), [TConfiguration](AwsStub.html#constructor.new_AwsStub.TConfiguration-1)> * Defined in packages/aws-sdk-client-mock/src/awsClientStub.ts:60 Properties ---------- ### send[](#send) send: SinonStub<[[AwsCommand](../types/AwsCommand.html)<[TInput](AwsStub.html#constructor.new_AwsStub.TInput-1), [TOutput](AwsStub.html#constructor.new_AwsStub.TOutput-1), any, any>], Promise<[TOutput](AwsStub.html#constructor.new_AwsStub.TOutput-1)>> Underlying `Client#send()` method Sinon stub. Install `@types/sinon` for TypeScript typings. * Defined in packages/aws-sdk-client-mock/src/awsClientStub.ts:58 ``` -------------------------------- ### AWS SDK v3 Client Mock API Documentation Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/classes/CommandBehavior.html API documentation for the aws-sdk-client-mock library, covering methods for mocking AWS SDK v3 client behavior. Includes details on setting responses, handling errors, and mocking any command. ```APIDOC ClientMock: // Mocks a specific command with a defined behavior. on(command: Command): // Sets a successful response for a single invocation. resolvesOnce(response: CommandResponse): ClientMock // Sets a default successful response for all subsequent invocations. resolves(response: CommandResponse): ClientMock // Sets an error response for a single invocation. rejectsOnce(error: Error): ClientMock // Sets a default error response for all subsequent invocations. rejects(error: Error): ClientMock // Mocks a command with a custom function. callsFake(fakeFn: (input: TInput, options?: TConfiguration) => Promise): ClientMock // Mocks a command with a custom function for a single invocation. callsFakeOnce(fakeFn: (input: TInput, options?: TConfiguration) => Promise): ClientMock // Mocks any command with a defined behavior. onAnyCommand(behavior: CommandBehavior): ClientMock // Resets all mocks. reset(): void // Gets all calls made to the client. calls(): Array<{ command: Command, args: any[] }> CommandBehavior: // Defines the behavior for mocked commands. resolvesOnce(response: CommandResponse): CommandBehavior resolves(response: CommandResponse): CommandBehavior rejectsOnce(error: Error): CommandBehavior rejects(error: Error): CommandBehavior callsFake(fakeFn: (input: TInput, options?: TConfiguration) => Promise): CommandBehavior callsFakeOnce(fakeFn: (input: TInput, options?: TConfiguration) => Promise): CommandBehavior CommandResponse: // Represents a successful response from a mocked command. // TCommandOutput: The type of the command's output. // Example: { MessageId: '123', $metadata: {} } ``` -------------------------------- ### Mock Behavior Order: Specific Matchers First Example Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/index.html Shows the consequence of declaring specific command matchers before wider ones. In this scenario, sends matching `myInput` will return ID '111', and all other `PublishCommand` sends will return '222'. ```typescript snsMock .on(PublishCommand).resolves({MessageId: '222'}) .on(PublishCommand, myInput).resolves({MessageId: '111'}); ``` -------------------------------- ### Mocking DynamoDB DocumentClient Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/README.md Demonstrates how to mock the `DynamoDBDocumentClient` using the `mockClient` utility, similar to other AWS SDK clients. It shows how to set up mock responses for commands like `QueryCommand`. ```typescript import { DynamoDBClient } from '@aws-sdk/client-dynamodb'; import { DynamoDBDocumentClient, QueryCommand } from '@aws-sdk/lib-dynamodb'; import { mockClient } from 'aws-sdk-client-mock'; 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', })); ``` -------------------------------- ### AWS Lambda with SNS Mock Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/README.md This example demonstrates how to mock an AWS SNS client within a Lambda function using aws-sdk-client-mock. It shows how to send messages to an SNS topic and return message IDs, with tests verifying the behavior and interactions. ```typescript 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 => { 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[]; } ``` ```typescript import {mockClient} from 'aws-sdk-client-mock'; import {PublishCommand, SNSClient} from '@aws-sdk/client-sns'; import {handler} from '../src'; const snsMock = mockClient(SNSClient); 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); }); ``` -------------------------------- ### Vitest Matchers for aws-sdk-client-mock Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/index.html Demonstrates how to import and use Vitest matchers provided by aws-sdk-client-mock for asserting AWS SDK client interactions. It also shows how to set up the expect library globally if not using Jest. ```typescript import 'aws-sdk-client-mock-jest/vitest'; import { expect } from 'vitest'; // a PublishCommand was sent to SNS expect(snsMock).toHaveReceivedCommand(PublishCommand); ``` ```javascript const {expect} = require("expect"); (globalThis as any).expect = expect; require("aws-sdk-client-mock-jest"); ``` -------------------------------- ### Mocking AWS lib-storage Upload Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/README.md Demonstrates how to mock the `@aws-sdk/lib-storage` Upload functionality by mocking the underlying S3 commands like `CreateMultipartUploadCommand` and `UploadPartCommand`. It covers both successful uploads and how to simulate failures by using `rejects()` on the mocked commands. ```typescript import {S3Client, CreateMultipartUploadCommand, UploadPartCommand, PutObjectCommand} from '@aws-sdk/client-s3'; import {Upload} from "@aws-sdk/lib-storage"; import {mockClient} from 'aws-sdk-client-mock'; const s3Mock = mockClient(S3Client); // for big files upload: s3Mock.on(CreateMultipartUploadCommand).resolves({UploadId: '1'}); s3Mock.on(UploadPartCommand).resolves({ETag: '1'}); // for small files upload: s3Mock.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(); // To cause a failure: s3Mock.on(PutObjectCommand).rejects(); s3Mock.on(UploadPartCommand).rejects(); ``` -------------------------------- ### Create AWS SDK Client Mocks Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/README.md Demonstrates how to create mock instances for AWS SDK clients, either for all instances or for a specific client instance. The default behavior of the mocked `Client#send()` method returns `undefined`. ```typescript import { mockClient } from 'aws-sdk-client-mock'; import { SNSClient } from '@aws-sdk/client-sns'; import { DynamoDBClient } from '@aws-sdk/client-dynamodb'; // Mock all SNSClient instances const snsMock = mockClient(SNSClient); // Mock a specific DynamoDBClient instance const dynamoDB = new DynamoDBClient({}); const dynamoDBMock = mockClient(dynamoDB); ``` -------------------------------- ### AWS SDK Client Mock API Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/index.html Details the API methods available on the mocked AWS SDK client, including methods for inspecting calls, managing mock state, and integrating with Sinon.js. ```APIDOC ClientMock: calls(): Call[] - Returns all received calls. call(index: number): Call - Returns the call at the specified index. commandCalls(command: CommandType, payload?: object, strict?: boolean): Call[] - Returns calls for a specific command, optionally filtered by payload. send: Sinon.SinonStub - The underlying Sinon.js stub for the client's send method. reset(): void - Resets the mock's state, behavior, and call history. resetHistory(): void - Clears only the call history, preserving mock behavior. restore(): void - Removes the mock and restores the original client behavior. mockClient(client: AWSClient, options?: { sandbox: Sinon.Sandbox }): ClientMock - Mocks an AWS client instance, optionally with a provided Sinon Sandbox. ``` -------------------------------- ### AWS SDK Client Mock API Reference Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/classes/AwsStub.html This section provides API documentation for the aws-sdk-client-mock library, detailing the methods available for mocking AWS SDK clients. ```APIDOC AwsClientStub: commandCalls(commandType: new (input: TCmdInput) => TCmd, input?: Partial, strict?: boolean): SinonSpyCall>[] - Retrieves recorded calls for a specific AWS SDK command. - Parameters: - commandType: The constructor of the AWS SDK command to match. - input: Optional. The command payload to match against recorded calls. - strict: Optional. If true, performs a strict match of the input payload (default: false). - Returns: An array of SinonSpyCall objects representing the recorded calls. on(command: new (input: TCmdInput) => AwsCommand, input?: Partial, strict: boolean = false): CommandBehavior - Defines the mock behavior for a given AWS SDK command. - Parameters: - command: The constructor of the AWS SDK command to mock. - input: Optional. The command payload to match for this mock behavior. - strict: Optional. If true, performs a strict match of the input payload (default: false). - Returns: A CommandBehavior object to configure the mock's response (e.g., .resolves(), .rejects()). - Example: snsMock.on(PublishCommand, {Message: 'My message'}).resolves({MessageId: '111'}); ``` -------------------------------- ### AWS SDK Client Mock API Documentation Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/classes/AwsStub.html Provides documentation for the methods used to interact with and control the behavior of mocked AWS SDK clients. ```APIDOC AwsStub: call(n: number): SinonSpyCall<[AwsCommand], Promise>[] - Returns the n-th recorded call to the stub. - Parameters: - n: The index of the call to retrieve. - Returns: The n-th SinonSpyCall object. calls(): SinonSpyCall<[AwsCommand], Promise>[] - Returns all recorded calls to the stub. - Can be cleared using resetHistory() or reset(). - Returns: An array of SinonSpyCall objects. callsFake(fn: (input: any, getClient: () => Client) => any): AwsStub - Sets a function that will be called on any Client#send() invocation. - Parameters: - fn: A function that takes Command input and returns a result. It can also access the client instance via getClient(). - input: The input object for the AWS command. - getClient: A function that returns the mocked client instance. - Returns: The AwsStub instance for chaining. - Example: snsMock.callsFake(input => { if (input.Message === 'My message') { return {MessageId: '111'}; } else { throw new Error('mocked rejection'); } }); - Example with getClient: snsMock.callsFake(async (input, getClient) => { const client = getClient(); const region = await client.config.region(); return {MessageId: region.substring(0, 2)}; }); - Implements Behavior.callsFake. ``` -------------------------------- ### Mocking DynamoDB DocumentClient Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/index.html Demonstrates how to mock the `DynamoDBDocumentClient` similarly to other AWS SDK clients, including specifying mock behavior for commands like `QueryCommand`. ```javascript 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' })); ``` -------------------------------- ### Mocking AWS SDK Clients Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/index.html Demonstrates how to create mock instances for AWS SDK clients, either for all instances or for a specific client instance. It also shows how to set default mock behavior where the mocked `Client#send()` method returns `undefined` by default. ```javascript const snsMock = mockClient(SNSClient); const dynamoDB = new DynamoDBClient({}); const dynamoDBMock = mockClient(dynamoDB); ``` -------------------------------- ### Using with Mocha Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/README.md Provides guidance on integrating aws-sdk-client-mock with the Mocha testing framework. It recommends calling `mockClient()` within `beforeEach()` to prevent mock overrides between test files. ```javascript // In Mocha tests: beforeEach(() => { mockClient(SNSClient); }); ``` -------------------------------- ### AWS SDK Client Mock API Documentation Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/classes/AwsStub.html This section details the API methods available in the AWS SDK Client Mock library for controlling mock client behavior, including setting responses, handling rejections, and resetting the stub. ```APIDOC rejectsOnce(error?: string | Error | AwsError): CommandBehavior Sets a failure response that will be returned from one `Client#send()` invocation. The response will always be an `Error` instance. Can be chained so that successive invocations return different responses. When there are no more `rejectsOnce()` responses to use, invocations will return a response specified by `rejects()`. Parameters: error: Optional error text, Error instance or Error parameters to be returned Returns: CommandBehavior Example: snsMock.rejectsOnce('first mocked rejection').rejectsOnce('second mocked rejection').rejects('default mocked rejection'); Implementation of Behavior.rejectsOnce Defined in packages/aws-sdk-client-mock/src/awsClientStub.ts:288 ``` ```APIDOC reset(): AwsStub Resets stub. It will replace the stub with a new one, with clean history and behavior. Returns: AwsStub Defined in packages/aws-sdk-client-mock/src/awsClientStub.ts:75 ``` ```APIDOC resetHistory(): AwsStub Resets stub's calls history. Returns: AwsStub Defined in packages/aws-sdk-client-mock/src/awsClientStub.ts:87 ``` ```APIDOC resolves(response: CommandResponse): AwsStub Sets a successful response that will be returned from any `Client#send()` invocation. Parameters: response: Content to be returned Returns: AwsStub Example: snsMock.resolves({MessageId: '111'}); Implementation of Behavior.resolves Defined in packages/aws-sdk-client-mock/src/awsClientStub.ts:223 ``` -------------------------------- ### AWS SDK Client Mock API Documentation Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/classes/AwsStub.html This section details the API for the AWS SDK Client Mock library, focusing on methods to control mock behavior for AWS SDK clients. It includes configurations for handling any command and for simulating rejected promises with custom errors. ```APIDOC onAnyCommand(input?: Partial, strict?: boolean): CommandBehavior Allows specifying the behavior for any Command with given input (parameters). If the input is not specified, the given behavior will be used for any Command with any input. Calling `onAnyCommand()` without parameters is not required to specify the default behavior for any Command, but can be used for readability. Parameters: input: Optional> - Command payload to match strict: boolean = false - Should the payload match strictly (default false, will match if all defined payload properties match) Returns: CommandBehavior Example: clientMock.onAnyCommand().resolves({}) rejects(error?: string | Error | AwsError): AwsStub Sets a failure response that will be returned from any `Client#send()` invocation. The response will always be an `Error` instance. Parameters: error: Optional - Error text, Error instance or Error parameters to be returned Returns: AwsStub Example: snsMock.rejects('mocked rejection'); Example: const throttlingError = new Error('mocked rejection'); throttlingError.name = 'ThrottlingException'; snsMock.rejects(throttlingError); ``` -------------------------------- ### Mocking Specific AWS Commands Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/classes/CommandBehavior.html The `on` method allows you to mock the behavior of a specific AWS command. You provide the command constructor and optionally an input object and a strict flag. This method is used to define how the mocked client should respond to a particular command. ```APIDOC on(command: new (input: TCmdInput) => AwsCommand, input?: Partial, strict?: boolean): CommandBehavior Parameters: command: The AWS command constructor to mock. input: Optional input parameters for the command. strict: Optional boolean to enforce strict matching of input parameters. Returns: A CommandBehavior instance to further define the mock response. Deprecated: Using this method means that the previously set `.on(Command)` was not followed by resolves/rejects/callsFake call. If this is legitimate behavior, please open an issue with your use case. ``` -------------------------------- ### Mocking AWS SDK Client Behavior Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/classes/AwsStub.html This section details how to mock the behavior of AWS SDK clients. It covers setting up fake responses for single calls or default behaviors, and inspecting the calls made to the mocked client. ```APIDOC callsFakeOnce(fn): Sets a function that will be called once, on any `Client#send()` invocation. Can be chained so that successive invocations call different functions. When there are no more `callsFakeOnce()` functions to use, invocations will call a function specified by `callsFake()`. Parameters: fn: ((input, getClient) => any) Function taking Command input and returning result Parameters: input: any getClient: (() => Client) Returns Client Returns any Returns: CommandBehavior Example: snsMock .callsFakeOnce(cmd => {MessageId: '111'}) // first call .callsFakeOnce(cmd => {MessageId: '222'}) // second call .callsFake(cmd => {MessageId: '000'}); // default Implementation of Behavior.callsFakeOnce Defined in packages/aws-sdk-client-mock/src/awsClientStub.ts:340 ``` ```APIDOC clientName(): string[] Returns the class name of the underlying mocked client class Returns: string Defined in packages/aws-sdk-client-mock/src/awsClientStub.ts:68 ``` ```APIDOC commandCall(n, commandType, input?, strict?): Returns n-th call of given Command only. Type Parameters: TCmd extends AwsCommand TCmdInput extends any TCmdOutput extends any Parameters: n: number Index of the call commandType: (new (input) => TCmd) Command type to match new (input): TCmd Parameters: input: TCmdInput Returns: TCmd Optional input: Partial Command payload to match Optional strict: boolean Should the payload match strictly (default false, will match if all defined payload properties match) Returns: SinonSpyCall<[TCmd], Promise> Defined in packages/aws-sdk-client-mock/src/awsClientStub.ts:141 ``` -------------------------------- ### Mocking SDK v2-style SNS PublishCommand Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/index.html Illustrates how to mock AWS SDK v3 calls made using the v2-style command method (e.g., sns.publish()) instead of the send() method. It requires mocking the specific Command class (PublishCommand) and the client (SNSClient) in the same way as other SDK v3 mocks. ```javascript import {PublishCommand, SNSClient} from '@aws-sdk/client-sns'; import {mockClient} from 'aws-sdk-client-mock'; // Example of SDK v2-style usage (not recommended by AWS): // 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', // }); const snsMock = mockClient(SNSClient); snsMock .on(PublishCommand) .resolves({ MessageId: '12345678-1111-2222-3333-111122223333', }); // Note: When mocking, you still use SNSClient and Command classes. ``` -------------------------------- ### Mocking AWS SDK lib-storage Upload Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/index.html Demonstrates how to mock the Upload class from '@aws-sdk/lib-storage' by mocking the underlying S3 commands like CreateMultipartUploadCommand, UploadPartCommand, and PutObjectCommand. This ensures that Upload#done() completes successfully or can be made to fail by rejecting mocked commands. ```javascript import {S3Client, CreateMultipartUploadCommand, UploadPartCommand, PutObjectCommand} from '@aws-sdk/client-s3'; import {Upload} from "@aws-sdk/lib-storage"; import {mockClient} from 'aws-sdk-client-mock'; const s3Mock = mockClient(S3Client); // for big files upload: s3Mock.on(CreateMultipartUploadCommand).resolves({UploadId: '1'}); s3Mock.on(UploadPartCommand).resolves({ETag: '1'}); // for small files upload: s3Mock.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(); // To cause a failure: // s3Mock.on(PutObjectCommand).rejects(); // s3Mock.on(UploadPartCommand).rejects(); ``` -------------------------------- ### Specifying Multiple Mock Behaviors Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/index.html Demonstrates how to define multiple mock behaviors for a single mock instance, covering different commands and payloads, including default behaviors. ```javascript 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' }); ``` -------------------------------- ### Reset and Restore AWS SDK Client Mock Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/index.html Provides information on managing the lifecycle of the mocked AWS SDK client using Sinon.js stub methods. Includes resetting mock state, history, and completely removing the mock. ```javascript clientMock.reset(); // Resets mock state and behavior clientMock.resetHistory(); // Clears only the call history clientMock.restore(); // Removes the mock entirely mockClient(client, { sandbox: mySandbox }) // Use a custom Sinon Sandbox ``` -------------------------------- ### Mock Behavior Order for Commands Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/README.md Demonstrates how the order of mock declarations affects command matching. Wider matchers should be declared first to avoid being overridden by more specific ones. ```typescript snsMock .on(PublishCommand, myInput).resolves({MessageId: '111'}) .on(PublishCommand).resolves({MessageId: '222'}); ``` -------------------------------- ### Mock AWS SDK Command Behavior Source: https://github.com/m-radzikowski/aws-sdk-client-mock/blob/main/docs/classes/AwsStub.html The `on` method is used to define the mock behavior for a given AWS SDK command. You can specify the command type, optional input parameters for matching, and whether the input match should be strict. This method returns a `CommandBehavior` object to configure the mock's response. ```typescript on(command: new (input: TCmdInput) => AwsCommand, input?: Partial, strict: boolean = false): CommandBehavior ```