Mocha tests in serverless AWS Lambda Express App
<p>I have a <a href="https://nodejs.org/en/" rel="nofollow">nodejs</a> App based on <a href="http://expressjs.com/" rel="nofollow">expressjs</a> that I am testing using <a href="http://gruntjs.com/" rel="nofollow">gruntjs</a> as task runner and <a href="https://mochajs.org/" rel="nofollow">mochajs</a> as test framework. Thus I have written component, integration and unit tests that are executed via <code>grunt test</code> or directly via <code>mocha test/component/v1/apiX</code> locally when I develop and on a test VM during deployment as part of a CI process.</p>

<p>Now when thinking about moving this app to an AWS Lambda aka <a href="https://aws.amazon.com/blogs/compute/going-serverless-migrating-an-express-application-to-amazon-api-gateway-and-aws-lambda/" rel="nofollow">going serverless</a> the following questions come to mind regarding my testing and CI process (note that I am going to use <code>aws-serverless-express</code> and thus will not have to write lambda functions explicitely):</p>

<p>1) How to implement the component / e2e tests that are done via HTTP api requests?</p>

<p>2) How to implement the integration &amp; unit tests that only load &amp; test a part of the app?</p>

<p>3) How to integrate both with a new CI flow that rejects deployment if any of the tests fail?</p>

<p>I consider question 1) mostly solved: there are many approaches to test AWS Lambdas from the outside. You can do lamba-to-lambda testing calling your lambda-to-test from a test-lambda directly or you can call the lambda-to-test via AWS API Gateway using HTTP from test-lambda as described <a href="https://aws.amazon.com/blogs/compute/serverless-testing-with-aws-lambda/" rel="nofollow">here</a>. You can also use the <a href="https://www.npmjs.com/package/serverless-mocha-plugin" rel="nofollow">serverless-mocha-plugin</a> for local lambda testing (if using <a href="https://serverless.com/" rel="nofollow">serverless</a>).</p>

<p>It is 2) where it gets interesting: once your lambda is deployed it is a black box. You cannot execute anything that is not declared as lambda interface explicitely. How do I save or re-implement my existing mocha unit &amp; integration tests?</p>

<p>Same for 3): how do you make your CI run <em>all</em> the tests on deployment and reject deployment if they fail?</p>

<p>Here my own approach: I would make my node app serverless only if in TEST environment. Simply let it work as classical node HTTP service by making all serverless changes conditional depending on environment. Since few changes are required this should be possible and maintainable. Now I can run the tests as usual locally and on deployment with grunt and mocha. Then I can still have final lambda-to-lambda testing if I want to be sure the serverless version works as well.</p>