Mock AWS SDK with Jest in TypeScript

white and brown animals near fence
Reading Time: 2 minutes
The AWS SDK is an incredibly powerful tool for managing resources in the cloud. But what if you want to use the SDK without having to deploy your code to AWS?

Mocking the SDK with Jest and TypeScript is a great way to quickly and easily test code that interacts with AWS services. By mocking the SDK, you can simulate requests and responses to ensure that everything works as expected.

This tutorial will walk you through how to create a mock of the AWS SDK and how to use it with Jest and TypeScript

When writing automated tests for applications that use Amazon Web Services (AWS) APIs, it can be difficult to test code that interacts with the AWS SDK. In order to make testing easier, you can use Jest in combination with TypeScript to mock the AWS SDK and simulate responses from the AWS service. This makes it possible to create reliable tests for your application without actually calling AWS APIs.

Advantages of mocking the AWS SDK

  • Avoid hitting AWS services will make you save so much money, especially if you have thousands of tests. Even if you use Localstack, your project’s configuration from checking out the code until you run it will take more time.
  • You tests will run faster

Disadvantages of mocking the AWS SDK

  • Slow down development process
  • Mocks for almost every scenario, otherwis,e it will call the real code (what we want to avoid)

Let’s see an example of how to mock the AWS SDK with Jest and TypeScript

The following code mocks two methods of SQS: receiveMessage and deleteMessage. If your code uses more methods of the AWS SDK you will have to mock all of them. Otherwise, your tests will call the real code.

import AWS from "aws-sdk";
jest.mock("aws-sdk");
const mockAws = AWS as jest.Mocked;

const mySQSMock = {
  receiveMessage: () => {
    return {
      promise: () =>
        Promise.resolve({
          Messages: [{ Body: "test" }],
        }),
    };
  },
  deleteMessage: () => {
    return {
      promise: () => Promise.resolve(),
    };
  },
};

describe("My test suite", () => {
  beforeAll(() => {
    mockAws.SQS.mockImplementation(jest.fn().mockImplementation(() => mySQSMock));
  });

  test("My test", async () => {
    // TBD
  });
});
, , ,

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


Leave a Reply

%d bloggers like this: