Mock it until it is real enough…

Tony Vu
2 min readMar 14, 2021

I finally got the approval from Telescope’s reviewers to start writing unit tests on my service. And it was not as straightforward as I would have thought…

My first struggle came from planning for my tests. I did not know how to start as my service includes a chain of middlewares as well as external HTTP requests. I literally spent three hours researching on the internet about testing with HTTP requests and middleware testing. Finally I decided that I should test whether my middlewares work correctly and whether the final json response body gave me what I expected.

During the process, I gotta learn more about supertest and nock . supertest is the HTTP client for testing environment and nock is a tool to mock HTTP request and response. I have also learned how to make the two tools work together. The hardest part of this testing is to convince yourself that I am on the right track because sometimes I felt like I was just doing random things without any concrete reasons. I felt proud of myself to be able to write these tests because they were quite hard to get for me.

Here are the results of many hours trying…

The joy when I run jest --coverage and it showed 100% is too much…

Isn’t this beautiful?

Thank you for reading.

Tony.

--

--