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
});
});