Prevent code duplication when writing unit tests with Jest .each

Fast Nguyen
TinySo
Published in
3 min readOct 22, 2021

Today I am going to show you how to prevent code duplication when writing unit tests with Jest .each.

Let’s get started!

Prevent code duplication when writing unit tests with Jest .each

Prerequisites

Problem definition

Given a string transformer function to convert a string to a kebab cased one

Code example for toKebabCase

And how your test cases are organized

Code example for duplication test cases

So you can see there are 5 test cases for toKebabCase utilities. Is there any way to make it better? shorter? and easier to maintain?

✅ YES, you can refactor the above test cases by using Jest it.each

it is an alias for test. So do not get confused when sometimes you see test instead of it. Refer to this. I prefer using it more than test because of the shortest name

Practices

Introduction

it.each signature

it.each signature

The table here is a tagged literal string in JavaScript. Why does it call table?

Because we organize our test cases like a table.

| var1 | var2 | expectedResult |
|------|------|----------------|
| 1 | 2 | 3 |
| 2 | 3 | 5 |
  • The 1st row contains variable name columns separated by |
  • From the 2nd row, each row contains variable value columns we pass to the test case as template literal expression ${value}, separated by | also.

Coding time

Okay, for now, you can refactor the above test cases to reduce code duplication.

Code example for it.each test cases

Wow, do you surprise that our test cases are shorter, easier to understand, and maintain

Wait, wait. Does it work? Yes, absolutely YES ✔.

Jest it.each test result

All test cases are passed now. You can see the GREEN ✅color (passed test cases), it can make your happy day at work 😁. Avoid the RED ❌ one (failed test cases) as little as possible if you want to get a long day 😂🤣

You might wonder if the describe.each exists?

✅YES, there is describe.each supported by Jest.

For describe.each, it's similar to it.each but for grouping test cases into collections.

You can explore more by going through the references section.

Conclusion

It is very cool to use it.each from Jest to make your test cases maintainable, avoid duplication.

Thank you for reading my article! I hope it is helpful for you. If you have any concerns or questions, do not hesitate to leave a comment below.

See you in the next article!

References

Also published in Prevent code duplication when writing unit tests with Jest .each (github.com)

--

--