How to mock and unit test serverless lambda invoking AWS and Dynamodb

Suranjana Basu
Jun 13 · 2 min read

This is a follow up to my earlier article on doing integration tests on lamda locally. But what about unit tests on serverless nodejs lamdas. The following is a guide to developing unit tests using dynamodb and lamdas.

One thing that I realized when I started on this task that there are no end to libraries. There is “lamda-tester”. There is ‘aws-sdk-mock’, mock-aws-sdk, aws-mocks. I tried a few of them and stopped until I could go no more. That is when I decided to simply use the tried and tested.. Nothing new, it’s built using mocha, chai, the mocking is using sinon and proxyquire was used to override dependencies. No fancy wiring of code needed as some of the earlier mentioned libraries called for.

So here is a quick guide:

Once you have sinon, mock out the AWS call . In my case it was the dynamodb call

var AWS;
var getSomeItemStub
(() =>{
getSomeItemStub = sinon.stub();
AWS = {

DynamoDB: sinon.stub().returns({
getItem: getSomeItemStub


Use proxyquire to override the dependencies:

testLambda = proxyquire( '../index', {
'aws-sdk': AWS

Create the sinon stubs:

getSomeItemStub.withArgs(sinon.match.any).yields(null, someObj);

Run the lambda using the regular mocha, chai framework:

it( 'test invocation', async() => {
getSomeItemStub.withArgs(sinon.match.any).yields(null, someObj);
const result = await testLambda.handler({"eventKey": "eventValue"}, context, (err, result) => {


One thing to keep in mind for unit tests is to reset the sinon stub after each method invocation:


That is it for unit tests. You can now test your lamda invocations using dynamodb locally using sinon stubs.