AWS SDK v3 Client Mock Jest Matchers

4.1.0 · active · verified Tue Apr 21

aws-sdk-client-mock-jest provides custom Jest matchers that extend Jest's `expect` API, specifically designed to simplify testing AWS SDK v3 clients when used in conjunction with `aws-sdk-client-mock`. It enables developers to assert on AWS SDK command invocations with readable and intuitive syntax like `toHaveReceivedCommand` or `toHaveReceivedCommandWith`. The package is currently at version 4.1.0 and maintains an active release cadence, with several minor and patch releases in recent months, often including beta cycles. Its key differentiator is the seamless integration into Jest's testing framework, allowing for robust unit and integration tests of AWS Lambda functions, frontend applications, and Node.js services interacting with AWS, without needing to manually inspect mock call arguments. Version 4.1.0 notably introduced support for Vitest, broadening its compatibility within the JavaScript testing ecosystem.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up `aws-sdk-client-mock` with Jest matchers to test DynamoDB `PutItemCommand` invocations, asserting on command types, call counts, and input parameters.

import { DynamoDBClient, PutItemCommand } from '@aws-sdk/client-dynamodb';
import { mockClient } from 'aws-sdk-client-mock';
import 'aws-sdk-client-mock-jest'; // Import to enable Jest matchers

describe('DynamoDB interactions', () => {
  let ddbMock: ReturnType<typeof mockClient>;
  const tableName = 'MyTestTable';

  beforeEach(() => {
    ddbMock = mockClient(DynamoDBClient);
  });

  afterEach(() => {
    ddbMock.reset();
  });

  it('should put an item into DynamoDB', async () => {
    ddbMock.on(PutItemCommand).resolves({ Attributes: { id: { S: '123' } } });

    const client = new DynamoDBClient({});
    const command = new PutItemCommand({
      TableName: tableName,
      Item: { id: { S: '123' }, name: { S: 'Test Item' } },
    });
    await client.send(command);

    expect(ddbMock).toHaveReceivedCommand(PutItemCommand);
    expect(ddbMock).toHaveReceivedCommandTimes(PutItemCommand, 1);
    expect(ddbMock).toHaveReceivedCommandWith(PutItemCommand, {
      TableName: tableName,
      Item: { id: { S: '123' } }, // Partial match works
    });
    expect(ddbMock).toHaveReceivedAnyCommand();
    expect(ddbMock).toHaveReceivedAnyCommandTimes(1);
  });
});

view raw JSON →