You rename a field during a refactoring, deploy, and an hour later a customer reports that their bike reservation returns a 500 instead of a friendly 409. Nothing in the infrastructure changed. The bug was in a decision your handler makes, and a test that runs in a fraction of a second on your laptop would have caught it.
That is why I think Lambda unit tests are the cheapest insurance in a Serverless project. In my full guide on Lambda unit tests with Vitest I build a small bike rental project from scratch. Here is the condensed version of what I learned along the way.
Test the decisions, not the wiring
A unit test checks a small piece of logic in isolation. AWS itself recommends many fast unit tests locally and only a few integration and end-to-end tests in the cloud. My rule of thumb for where they pay off: wherever your code makes decisions. Validating input, choosing status codes, translating errors, reporting partial failures in a batch. These are the places that break during refactorings, and often exactly where tests are missing.
Pure wiring, like "event in, item into DynamoDB", I would rather test once in the cloud, because that is where real permissions apply.
Shape your handler so it can be tested
Before writing a single test, it is worth looking at the code. Two things make a huge difference:
- Keep the exported handler a one-line adapter. The logic lives in a factory function that receives its dependencies, such as the DynamoDB client, the current time and an ID generator. In tests you pass fixed values, so every run produces the same result.
- Only catch the errors you understand. A failed DynamoDB condition becomes a 409. Everything else is thrown on, so Lambda marks the invocation as failed and your alarms fire.
Mocking the AWS SDK with aws-sdk-client-mock
For the SDK calls I use aws-sdk-client-mock together with its Vitest matchers. You attach a mock to a client, define how it should respond, and afterwards verify exactly which command was sent. A simplified example:
const dbMock = mockClient(db);
beforeEach(() => dbMock.reset());
it('returns 409 when the bike is already taken', async () => {
dbMock.on(PutCommand).rejects(
new ConditionalCheckFailedException({ message: 'taken', $metadata: {} }),
);
const res = await handler(eventFor({ bikeId: 'b-1' }));
expect(res.statusCode).toBe(409);
expect(dbMock).toHaveReceivedCommandWith(PutCommand, {
TableName: 'reservations',
});
});
Forgetting reset() in beforeEach is a classic: suddenly the third test still sees the calls from the second one.
Partial batch failures deserve their own tests
The second handler in the guide reads reminders from SQS and publishes them via SNS. Lambda receives up to ten messages per invocation. If one fails and the handler throws, the whole batch goes back to the queue by default, including the messages that already succeeded. With partial batch responses (ReportBatchItemFailures) you only report the failed message IDs. That logic is easy to get subtly wrong, so I test it with stored event files and check both the returned failures and the number of SNS calls.
Where unit tests stop
I disagree with the idea that you can fully secure a Serverless application locally. Mocks know nothing about IAM. A missing dynamodb:PutItem permission, a wrong queue ARN or a timeout that is too short will never show up in a green test run. My split: many fast unit tests for decisions and error paths, a few integration tests in a separate cloud environment for permissions and wiring.
And one note on AI assistants: they write tests like these in seconds. That only helps if you decide upfront which cases matter, instead of asking for "tests for this file".
What the full article covers
- The complete Vitest setup for TypeScript Lambdas, including types and matchers
- Both handlers and their full test suites, including the
it.eachvalidation tests - Mocking an instance versus a class, and reading environment variables safely
- Deployment with Serverless Framework, coverage measurement and FIFO queue pitfalls
- An FAQ on Vitest vs. Jest, LocalStack and AWS SDK v2
Read the complete guide: Lambda unit tests with Vitest: test TypeScript handlers
๐ This is the condensed version. The full article on sascha-ms.de goes deeper โ with all code samples, diagrams and a short knowledge check.
๐ Next step: Curious what your own Lambda functions cost? Try my Lambda cost calculator โ it runs right in your browser.
๐ฌ Stay updated: New articles on serverless, AI and leading tech teams via RSS, browser push or the weekly newsletter (in German).
Originally published on sascha-ms.de. More articles on serverless, AI in everyday development and leading tech teams: sascha-ms.de/en
Top comments (0)