Search code examples
node.jsamazon-web-servicesnpmmocha.jsaws-sam

Unit testing AWS Lambda that uses Layers - Node JS app


I have a SAM application with a bunch of Lambda functions and layers, using Mocha/Chai to run unit tests on the individual functions.

The issue is, that I am also using Layers for shared local modules.

The SAM project structure is like this..

functions/

  • function-one/
    • app.js
    • package.json
  • function-two/
    • app.js
    • package.json

layers/

  • layer-one/
    • moduleA.js
    • moduleB.js
    • package.json
  • layer-two/
    • moduleC.js
    • package.json

According to AWS once the function and layers are deployed, to require a local layer from a function you use this path...

const moduleA = require('/opt/nodejs/moduleA');

However, that running locally as a unit test wont resolve to anything.

Any idea on how to resolve the paths to the layer modules when running unit tests?

I could set an ENV var, and then set a base path for the layers based on that, but I was wondering if there was a more elegant solution I was missing...

Is there any way to alias the paths when running Mocha ?

other options are to use SAM INVOKE but that has massive overheads and is more integration testing...


Solution

  • I swapped over to using Jest which does support module mappings

    In the package.json...

    ... 
    "scripts": {
       "test": "jest"
    },
    "jest": {
        "moduleNameMapper": {
          "^/opt/nodejs/(.*)$": "<rootDir>/layers/common/$1"
        }
      }
    ...