From my experience, local testing is difficult but not impossible and does not need bloated tools such as localstack that try to emulate AWS services. The thing to bear in mind about Lambda functions is that ultimately they are just functions that need parameters passed to them and that should generate a certain expected output with those parameters. This means we can use tools as simple as Mocha (and equivalents in other runtimes) and just do unit tests to help execute code locally. This does not mean you have to go down the rabbit hole and build out a full suite of unit tests (you can of course do so if you want), but using a tool such as this means you can now execute your function code by passing it parameters repeatedly and tie that execution into a debugger.
The only remaining issue is interaction with AWS services and this is where mocking steps in. And I know a lot of folks immediately hear mocking and think its bad practice. Mocking is ONLY bad practice if you use it to bypass elements you should actually be testing such as your own classes. But why would you want to test that making a
putItem call to DynamoDB is successful? When in reality what is more useful is to be able to test what happens when that service fails. You can mock success and failure of AWS services and therefore test that. You cannot test failure if you are tied to the actual DynamoDB service and testing failure with a locally emulated version is not a cake walk either.
“But Gareth … that all sounds so painful to setup” I hear you say. Not really. There are existing Node modules and serverless plugins you can use as well as this hand dandy blog post I wrote a few months back to guide you in setting all this up. At the end you will have a way to repeatedly execute your function code with a debugger tied in and the best part is, its a unit test … you can run this in CI/CD as well.
- Your machine does not get bloated with emulated services
- You no longer need to deploy code into the cloud to realise you have a syntax error, spend 10 seconds fixing and another minute deploying.
- You can now test offline as mocking keeps everything local
- Every service is entirely modular and for a new developer to get started with an existing service is just
npm install and their “testing environment” is all setup and ready to go.
- As a developer you are no longer relying on tools like serverless-offline which only help test HTTP endpoints, and this means you are now open to explore the breadth and depth of events in AWS, making your app richer in every way.
- Probably a bunch of benefits I didn’t cover.