Real-world Node.JS TDD example
--
A walkthrough of a real-world example of applying TDD to develop a Node.JS lambda function. Featuring graphQL API call and upload to an Amazon S3 Bucket.
I was recently asked to develop a little lambda function to periodically generate XML sitemaps and upload them to an Amazon S3 Bucket. I thought it was a perfect example of a TDD walkthrough. The scope is broad enough to cover interesting use cases and showcase some unit testing patterns.
Who should read this post ?
This post is not intended for TDD beginners. We’re going to take some shortcuts, and it is not idiomatic TDD, just an opinionated version of it. However, you don’t need to be a TDD expert, this post is for you if:
- you already played with TDD and struggle to use it in a real project
- you write tests that keep breaking every time you make the slightliest change and want to know how to write less brittle tests
- you struggle with testing I/O (web API calls, saving to a database, uploading file, etc.)
- you didn’t find an alternative to “interface” in javascript but still want to write maintainable and easy to test code
- you’re wondering how to use both outside-in and inside-out TDD techniques
This post is a complete walkthrough, so it’s a long read. Here is what we’re going to talk about :
- The specifications for this project
- Why it is important to think before to code
- The importance of separating busines logic from I/O code (writting pure functions for business logic, and keeping the I/O at the edges of the application.)
- Outside-in testing : creating a trivial application layer to drive the implementation (how to hardcode input and output, how to write a test with the arrange/act/assert pattern)
- Extracting business logic from the application layer
- Keeping our tests DRY and maintainable by creating test data factory
- Implementing the “input infrastructure”, the graphQL API call, guided by Focused Integration tests (how to create a test server with configurable responses)
- Exploring the Null Object…