DEV Community

Discussion on: Unit Testing AWS Lambda Functions in Node.js

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.