Mock DynamoDB in Typescript
In 2021 one of our team priorities is to move toward Serverless architecture. It is tricky to build the unit tests on top of the AWS services. It dragged me a couple of hours to figure out the most comfortable way to mock the DynamoDB functionality.
aws-sdk-mock has a pretty detailed readme and examples for a quick start. The approach is intuitive and clean. When I messed around it in Typescript and Jest, there were a few hiccups that paused me a while without a useful error message. Then I realized that the order of invocation caused unexpected behavior.
Based on the example in the readme, I would emphasize the order of steps to get successful behavior.
Step 1: Mock the AWS instance
AWSMock.setSDKInstance(AWS);
Step 2: Mock the DynamoDB function, e.g. put
AWSMock.mock(
‘DynamoDB.DocumentClient’,
‘put’,
(params: UpdateItemInput, callback: Function) => {
callback(null, { pk: ‘foo’, sk: ‘bar’ });
},
);
The first two parameters are apparent. ‘DynamoDB.DocumentClient’ is the module, and ‘put’ is the function to mock. The third parameter is a callback function to simulate an asynchronous response with your desired data.
Step 3: Create a DynamoDB instance with the mocked AWS instance.
const mockDynamoDB = new AWS.DynamoDB.DocumentClient({
apiVersion: ‘2012–08–10’,
});
We’ll use the proxied AWS to create a new instance for our further action. It must follow step 2. Otherwise, the instance will call on the real DocumentClient and end up with a confusing error message.
Step 4: To test the mocked put function.
const input = { TableName: ‘’, Item: {} };expect(await mockDynamoDB.put(input).promise()).toEqual({
pk: ‘foo’,
sk: ‘bar’,
});
Now the mockDynamoDB.put function is successfully mocked with your desired outcome.
Step 5: Restore the mock
AWSMock.restore();
To prevent unexpected effect to the rest of your tests, it is always brilliant to reset the mocked work.