AWS SDK Mocking Library for JavaScript v2

6.2.2 · maintenance · verified Sun Apr 19

aws-sdk-mock is a JavaScript/TypeScript library designed to facilitate unit testing of applications that interact with the AWS SDK, specifically targeting AWS SDK for JavaScript v2. It enables developers to replace actual AWS service calls with predefined responses or custom functions during tests, preventing unintended interactions with real AWS infrastructure. The current stable version is 6.2.2. While there isn't a strict time-based release cadence, the project is actively maintained, with recent minor updates addressing dependencies and security vulnerabilities (e.g., v6.2.0 addressing CVE-2024-45296) and a significant TypeScript rewrite in v6.0.1. It differentiates itself by leveraging Sinon.js internally to create robust mocks for AWS service methods like S3.getObject or DynamoDB.putItem, offering explicit `mock`, `restore`, and `remock` functions. A key limitation and differentiator is its primary focus on AWS SDK v2; for AWS SDK v3, direct mocking of modular clients might be preferred, reducing the need for this library.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to mock an AWS SDK v2 S3 client's `getObject` method, execute a call, and then restore the original method.

import { S3 } from 'aws-sdk';
import { mock, restore } from 'aws-sdk-mock';

// Ensure aws-sdk@2 is installed (e.g., `npm i aws-sdk@2`)
// This example uses an async IIFE for demonstration.

(async () => {
  const bucket = 'my-mock-bucket';
  const key = 'test-file.txt';
  const mockData = { Body: Buffer.from('Mocked content!') };

  // 1. Mock an S3 service method
  mock('S3', 'getObject', (params, callback) => {
    console.log(`Mocking S3.getObject for ${params.Bucket}/${params.Key}`);
    callback(null, mockData);
  });

  // 2. Use the AWS SDK client as usual
  const s3Client = new S3();
  const result = await s3Client.getObject({ Bucket: bucket, Key: key }).promise();

  console.log('Received mocked data:', result.Body?.toString()); // Expected: 'Mocked content!'

  // 3. Restore the original method after the test
  restore('S3', 'getObject');

  console.log('Mock restored. Subsequent calls would use original S3 or fail without credentials.');
})();

view raw JSON →