DEV Community

Unit Testing AWS Lambda Functions in Node.js

Alex Manarpies on December 09, 2018

Writing backend code - like web services or anything else really - with AWS Lambda functions is amazingly easy, in particular when you choose Node...
Collapse
 
harkinj profile image
harkinj

Great info. In your sample test does the require('../index') not load the non mocked lambda code first before sinon (via beforeach) gets a chance to mock it out? Is there a github repo? Thanks for your time.

Collapse
 
jarroo profile image
Alex Manarpies

The deps property does get created first, along with the rest of the lamdba, but it gets overwritten in beforeEach. Because the deps property is wrapped in a Promise, it's not actually run immediately, allowing it to be overwritten by the test if necessary.

Collapse
 
harkinj profile image
harkinj

Thanks for the info. In the example given will running the unit tests still result in connecting to the dynamodb database via 'const documentClient = new AWS.DynamoDB.DocumentClient()'

Thread Thread
 
jarroo profile image
Alex Manarpies

I double-checked by setting a breakpoint and it's not being triggered. Notice that the deps property is actually a function:

exports.deps = () => { // notice the closure syntax
  const AWS = require('aws-sdk')
  const documentClient = new AWS.DynamoDB.DocumentClient()

  return Promise.resolve({
    dynamoBatchWrite: params => documentClient.batchWrite(params).promise()
  })
}

.. its body contents should only be run when deps is invoked as a function (in this case async).

Thread Thread
 
harkinj profile image
harkinj

Perfect, thanks for your time and this great article.

Collapse
 
nairp_onalytica profile image
Parag Nair

Alex, you are calling const deps = await exports.deps() inside the handler. Doesn't that mean every time the handler is executed, it will create an instance of AWS.DynamoDB.DocumentClient. Isn't it recommended for Lambdas to have all your initialization code outside the handler as I assume behind the scenes, it creates a container and stays warm till you keep hitting it periodically. Any initilization outside the handler is called once per container. Just a thought.

Collapse
 
grunlowen2 profile image
grunlowen2

Thanks for the suggestions here. I implemented something similar after reading this, but I'm wondering if there is really a need for the promise. In my case, what I did was create an exports.deps that returns an object like { s3: new AWS.S3() } and then I also created an exports.initDeps, which gets the object from exports.deps, and then assigns it to the top level variable. I have a fairly complex lambda, and I wanted to be able to test functions independently. So now the handler is the only function that calls exports.deps, and in my test code I overwrite initDeps, and then call any of the functions.

Collapse
 
mk0y8 profile image
Marko Jakic

Would this work with AVA tests where tests are run in parallel?