TDD + data driven with Jest

Sergio Ausín
StubHub Product & Tech Blog
2 min readNov 2, 2020

--

During my years as developer, I have faced several troubles in production due to bugs. Bugs are everywhere and a lot of people have spent hours and hours trying to fix them. For me, this is a huge problem because I love to sleep, and I cannot sleep well if I have doubts about the quality of my code. Because of this, I started some years ago to study how to sleep well, which came down to learning about testing my code.

My first step in the testing world was doing tests after the code. This improved a lot the quality of my code. However, it highlighted another problem: my tests were influenced by my code. To avoid this, I started to learn about TDD.

When we do TDD, our starting point are some scenarios/specifications which are written as tests. After that, our solution starts to be developed until we can assure that our code is doing what we can to match those scenarios. Let’s look at the example of a simple project in JS.

First of all, we are going to create our sample project just running these commands:

mkdir tdd
cd tdd
npm init

When we run npm init, the terminal will ask us some questions to create our project. Once we’ve answered them, just run:

npm install --save-dev jest

Next, we update our test command in package.json to:

“test”: “jest”

After that we are going to create two files: calculator.js and calculator.test.js.

After this, when we run npm run test, it will fail and show this result:

Now, we can write the correct code to match this scenario:

JS is not a typed coding language, as the developers out there know, so anyone could try to use our method just by passing them string, null, undefined… We could create more tests to check this, which will create another problem: code reusability and maintainability. To fix this problem, we could use the data-driven testing approach. It will make our testing process as simple as adding a new line. Let’s change our test to a data-driven testing approach.

Now we can add as many tests we want just by adding a line. I will add some extra lines to check different edge cases:

Once we run this, our report will be the following:

Finally, we change our code to make it work properly:

As time has passed, here in Stubhub we have been able to reduce the quantity (and severity) of issues that have appeared. My code looks much better (you can ask my colleagues :P), and the QA department is not a grumpy cat anymore. Even with these actions, there is a long way to improve the quality of our code and we will continue to improve our process to take care of it.

--

--

Sergio Ausín
StubHub Product & Tech Blog

Angular developer. Monorepository and ESLint lover. Geek and guitar player.