Two methods to mock AWS Services in JEST

Ranjani Vraman
Missguided Tech Blog
3 min readJul 19, 2021
Real Vs Mocked

In the past, I’ve found it difficult to mock AWS services for unit tests and after some research, there seems to be many ways of doing this. I’ve chosen 2 ways to Mock AWS services in unit tests that worked for Missguided, these are:

1. Writing Manual mocks in JEST

2. AWS-SDK-MOCK (npm module)

Let’s start with the function below that returns an item from DynamoDB. We can use the same function as an example to demonstrate both methods.

METHOD 1: Writing manual mocks in JEST

JEST framework allows us to write manual implementations of the original classes, these are called Manual mocks. This can be done in a few simple steps such as creating manual mocks and using them in the unit tests.

Step 1: Create the folder structure

I created a __mocks__ folder alongside node_modules folder and added a file called dynamodb.ts which will hold the mocked class.

/__mocks__/aws-sdk/clients/dynamodb.ts

Step 2: Add the code

Inside the file dynamodb.ts, we mock the DocumentClient class to return a get method which we implement using jest’s mockImplementation method as in line 3

Step 3: Using Manual Mock in unit tests

We reference the mocked class in the unit test on line 7 as below

Every time we run this unit test with jest we will use the mocked service instead of the real service.

METHOD 2: Using aws-sdk-mock module

The second method is to install and use a npm module called aws-sdk-mock. This is used for unit testing by automatically mocking the dependant AWS services such as DynamoDB, SNS topic, SQS etc.

This can be done in two simple steps, which are

Step 1: Install aws-sdk-mock as a project dependency

To install the dependency run one of the following commands from the project root

npm install aws-sdk-mock
yarn add aws-sdk-mock

Step 2: Add unit test to mock AWS instances

Once we have installed the aws-sdk-mock module, we get access to the mock AWS functions which each take three parameters which are

1. The service to be mocked e.g. SNS topic.

2. The method to be replaced e.g. publish().

3. The string or function to replace the method e.g. an anonymous callback function.

For more detailed documentation refer to this link https://www.npmjs.com/package/aws-sdk-mock

We have found method 1 to be more flexible, but method 2 to be a little easier.

For Missguided both methods were useful to unit test without having any dependency on the AWS services like DynamoDB, SNS topic, SQS etc.

I hope this blog post was useful for you.

Thanks for reading!

Have a nice day!

--

--

Ranjani Vraman
Missguided Tech Blog
0 Followers

Senior Software Engineer in Missguided