Mock AWS SDK with Jest in TypeScript

An example mocking some SQS methods


Jul 31, 2021
featured image

Advantages

  • Avoid hitting AWS services will make you save so money, specially if you have thouthands of tests. Even you can use Localstack, that will increase you project's configuration from checking out the code until you run it

Disadvantages

  • Slow down development process
  • Mocks for almos every scenario
      
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
  });
});

      
    

Photo by Thomas Bormans on Unsplash


typescript javascript testing