loading...

TDD: Test Drive Your Code!

vblaha profile image vblaha Updated on ・2 min read

img
In the past week we've spent a bit of time in class writing unit tests and functional tests using Mocha and Chai, then pairing with Sinon to mimic a server. In this post, I will cite an opensource project I've contributed to on Github, using Jest to pair with React. To look at what test-driven development means, let's take a closer look.

Test-Driven Development (TDD) is beginning the coding process by writing tests first. Writing tests before writing the corresponding code helps define the parameters and use of the function, resulting in more modular, reusable pieces of code. Done properly, good unit tests can serve as documentation to other coders by providing them with a design of how you wanted your function to behave. Good unit testing can make it easier to refactor your code and look at it objectively each step of the way.

In the following example, this unit test has one purpose: to see if the capitalized word will be tallied on a counter just like the uncapitalized match:
img
The test begins by giving us a short description of what the function should do if our circumstances are met. It then defines parameters to test and the number of times the parameters should be found.

The above test helps define the .toLowerCase() method in the counter function found below:
img

You can build a suite of tests in a similar fashion to isolate instances in a function, like the following:

img

This is just a short intro to writing tests. More to come! As always, questions, comments and suggestions for improvement are always welcome. Thank you for reading.

Posted on by:

vblaha profile

vblaha

@vblaha

Current student at Georgia Institute of Technology Full Stack Web Development Bootcamp

Discussion

pic
Editor guide