All Articles

JavaScript TDD Automate your Inputs

Recently embracing Test-Driven-Development (TDD) has crushed some of my bad coding habits and forged better ones. Among those better habits is the concept of automating inputs in my unit tests.

Let’s do it together!

Use npm init -y and install Jest as a devDependency.

In your package.json, fill out the test NPM script with jest --watchAll. This tells Jest to rerun our unit tests on every change.

The functionality

We’re going to write a function called randomBetween; it generates a random number between two numbers.

And since we’re preaching TDD, we’ll write the test first! Add a file called randomBetween.spec.js. Here’s the spec code.

The test is pretty simple: make sure randomBetween(1, 10) returns a number between 1–10. Let’s run Jest in terminal with npm test.

Oh yeah, we didn’t define randomBetween…let’s do that! Create a new file called randomBetween.js. Here’s the code.

Now import it and watch your test pass with flying colors.

That’s great, but…

…I’m not a fan of testing this way. The whole point of a unit test is to avoid manual work, but we’re manually giving randomBetween its input.

Our test only passes in that exact scenario. What if we call randomBetween more than once or provide a different range? Are we also writing those scenarios by hand? No thanks.

Loops for days

We can automate our inputs with loops! All we need is the ability to run a function n times and see the results as an array.

I personally use the times function from Ramda, but we can write a simple times for our purposes. Create a new file called times.js. Here’s the code.

It calls fn(n) n times and returns an array of the results. Try it in your browser console.

Back to the tests!

Just like that, we have 1000 numbers between 1–10. And since it’s an array, we can use the every method!

MDN Docs:

The every() method tests whether all elements in the array pass the test implemented by the provided function.

Tests every element, huh? Perfect.

All done

Another benefit is your test inputs will always be unique, because you’re generating 1000 random numbers every single time.

If you want to get really crazy, randomize the range you call randomBetween with. O_O”

This idea’s made unit testing much more enjoyable for me. After planning a function’s test, hammer it with tons of different inputs and see what breaks. That’s how you ensure truly bulletproof code. Let me know if this helps, or if you’ve already been doing this.