Testing Lambda functions can be tricky. A typical cycle is to assume everything is fine, push up, get stuck, debug and make corrections locally, then push up again. A better approach would actually be to test locally before pushing up.
To be able to test this locally, we need to be able to pass in the required event, context and callback parameters. Interestingly, by looking into the event and context objects and of course knowing callback is just a function passed in to return information, we can create similar objects and use them for our local test.
Let’s start with event. This is used to pass event data to the function. The data will depend on the event source connected to your Lambda function. You can find a list of sample events published by event sources here. Here is the sample event data for SNS for example:
For me though, (I use this on TFP to send data across the workers), two things:
The only value I’m interested in from the event data is event.Records.Sns.Message
Message is a stringified JSON object.
Based on these, I can create my event object as this:
Next is the context parameter. We can see all the keys of the context object in this document. Let’s create a similar object.
callback is the easy one.
Now that we have the 3 required parameters. We can put everything together.
And there we have it. If there is any issue with the function, we can easily know and debug. One tip during test is to do lots of console logging within your function to note execution points and see the data that is passed around.
My name is Opeyemi Obembe. I build things for web and mobile and write about my experiments. Follow me on Twitter–@kehers.