We lost $ 20.5K in one day and how we could have saved it… hint: better automated testing with node js, mocha, nock and proxyquire. With code coverage by istanbul
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
We lost $ 20.5K in one day and how we could have saved it… hint: better automated testing
1. @geshan
We lost $ 20.5K in one day and
how we could have saved it…
hint: better automated testing
Geshan Manandhar
Senior Software Engineer (THE ICONIC)
6. @geshan
One day early 2017 we deployed a new app
rewrite and lost 20.5 K USD in ~24 hours? How?
With 5 or less lines of code
6
7. @geshan
These 5 lines of code
return isFirstShipmentofOrder(connection,
orderData.fk_sales_order).then(isFirstShipment => {
isFirstShipment = isFirstShipment[0]; //this was always false
let serviceFee = isFirstShipment ?
parseFloat(orderData.shipping_amount) +
parseFloat(orderData.payment_fees) : 0; //so this was always 0
…
}7
8. @geshan
Not blaming anyone
▪ Mysql2 library was not the issue it was us and not having
comprehensive tests (process)
▪ const [rows, fields] = await connection.execute('SELECT *
FROM `table`... I think we misread fields with rows (don’t
clearly remember)
▪ What I remember though:
▫ 2 software engineers with relatively less experience with
backend JS and JS concepts like promise
▫ Testing was in place but not enough to cover this service
fee case
▫ Noone was fired, we fixed it and did a postmortem.8
11. @geshan
This talk is about
testing not the story
▪ Goals:
▫ Use Mocha, Nock and Proxyquire to test an
Express JS API (why not Jest, I am old school)
▫ The API will
■ Have a DB with read/write operation
■ Call an API for data
▫ Use Istanbul/nyc for code coverage
11
12. @geshan
Minimalist approach
(opinionated)
▪ Using assert (not chai) - comes in node core itself
▪ Not using Sinon or any other library for mocking
▪ Stubbing responses per use case
▪ Rewire package might be used to test “private”
methods (but do you want to do it?)
▪ For bigger projects it may not work (let’s talk
“micro” services)
12
13. @geshan
Currency Converter
API
▪ Let's start with a simple app a currency converter
API
▪ It reads and write to a DB (MySQL)
▪ Call an external API for the currency rates
▪ Runs at: https://currency-api-nodejs.now.sh
▪ Code at: https://github.com/geshan/currency-api
13
15. @geshan
Conclusion
▪ Write tests for confidence not 100% code coverage
▪ Always thoroughly test things that involve “Money” (don’t
lose money due to one missing test :) simple)
▪ Use the tools of your choice, meet the goal. Tools are just one
way to get to the goals. Wanna use Jest go for it.
▪ Write tests first (TDD) or tests last (test supported) but
always write them
▪ Setup a continuous integration environment to get the
feedback loop running, try out Werkcer CI (free)
15