To Test A System, Isolate Side-Effects 🔊

Taking out side-effects is one of the best ways to build testable code

The picture of a boxing match between two male fighters. Their faces are outside the frame. The fighter on the left has dispatched a left hook to the fighter in the right. The fighter on the right is wearing a red short with a small symbol of the Soviet Union.
Listen to the audio version!
The runnable code with tests that shows Nock stubbing a request to get a static list of posts.
A diagram that shows a block on the left with the caption "create list of posts." One arrow points to a block with the caption "posts response." The other arrow points to a block with the caption "fetch." The block with the caption "fetch" has one arrow that points in the direction of a block with the caption "HTTP server." The last arrow is interrupted with the label "Nocked."
The diff showing the changes to the response type handling inside the function "create list of posts." The function has changed the response type handling from html to JSON. Click here to see the code and the failing test.
The diff showing the changes of the request URL inside the function "create list of posts." The URL from the request changes from "blog/posts" to "blog/articles." Click here to see the code and the failing test.
The runnable code with the tests that shows the Data Source decoupled from the logic to create the list of post titles.
A diagram that shows a block on the left with the caption “list of post titles.” One arrow points to a block with the caption “In-Memory Data Source.” The other arrow points to a block with the caption “HTTP Server Data Source.”
The test code that adds the functionality to filter the list of post titles. The filter runs before the code generates the HTML list.
The test code which injects a “get request” into an "HTTP Server Data Source." The “get request” returns a static response. The test asserts that the code creates an HTML list of posts title correctly. It uses all the components necessary to produce the expected result.
The test code which injects a “get request” into an “HTTP Server Data Source.” The "get request" returns a static response. The test asserts that the method "find posts title" from the "HTTP Server Data Source" returns the correct result.

If not used sparingly, Nock can create a Nock Hell.

I believe ideas should be open/free. This is a non-profit initiative to write about challenging stuff you won’t find anywhere else. ~7 min post every few weeks.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store