Unit Testing AWS Lambda Functions in Node.js

Unit Testing AWS Lambda Functions in Node.js

When I started to write Lambda functions using Node.js, I didn’t find frameworks that I enjoyed using. I ended up writing my own helper utilities to make testing Lambdas easier and less painful.

The Old Way

Let’s test with my basic go to frameworks, Mocha and Chai, and use a very simple Lambda function just to facilitate the examples in this article.

The following represents the Lambda function that we want to test:

To cover the code fully, we would want to test the name being equal to ‘Richard’ and ‘rhyatt’, the name being something else and just for fun the name being not set (undefined).

So our test code, using some loops for valid/invalid cases would look like

Running the above test against our handler, we should get the following output:

Great our tests work and if were to run a code coverage tool, like istanbul, we would have full coverage. But if the code was a little more complicated, we might be in for some real trouble.

New Way — Using Lambda Tester

After writing several versions of test utilities, discussing best practices with other developers, and them repeatedly asking to use my test code, it dawned on me that others were experiencing a similar pain (or just not writing tests!). I open sourced my tool under the name “lambda-tester” and it’s available via NPM. To add it to your code:

npm install lambda-tester --save-dev

And now we’re off to make testing Lambda handlers easier and less painful. The following code is the same set of tests, but this time we’re using lambda-tester:

And when we run it:

Our new set of tests are 46 lines long compared to the 61 in the old method. If our Lambda expression actually did something and was more complicated, we might see a larger difference in the amount of code.

Things to Remember

When using lambda-tester it is *important* that your it() has the done parameter that allows the tests to run asynchronously. Failing this step will cause the lambda-tester to not work as expected.

That’s it for now, but if you’re writing lambda handlers check out lambda-tester’s sister project ‘vandium’ — simplifies writing and securing lambdas.

Source Code

The source code for this article is located at https://github.com/vandium-io/using-lambda-tester.


This article was originally published on medium.

Fixed the article - LinkedIn Pulse editor was accepting my code blocks but not rendering when pushed. Added screenshots from Atom editor

Like
Reply

The code is not displayed inline within the linkedin article, I've tried Chrome and Firefox, was there a formatting problem?

To view or add a comment, sign in

More articles by Richard Hyatt

Others also viewed

Explore content categories