Prevent code duplication when writing unit tests with Jest .each
Today I am going to show you how to prevent code duplication when writing unit tests with Jest .each
.
Let’s get started!
Prerequisites
- Know how to write test cases in Jest
- Have basic TypeScript knowledge
- Understand template literal syntax of JavaScript
Problem definition
Given a string transformer function to convert a string to a kebab cased one
And how your test cases are organized
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 fortest
. So do not get confused when sometimes you seetest
instead ofit
. Refer to this. I prefer usingit
more thantest
because of the shortest name
Practices
Introduction
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.
Wow, do you surprise that our test cases are shorter, easier to understand, and maintain
Wait, wait. Does it work? Yes, absolutely YES ✔.
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
- JavaScript template literal
- Getting started with Jest
- Jest test.each`table`(name, fn, timeout)
- Jest describe.each`table`(name, fn, timeout)
Also published in Prevent code duplication when writing unit tests with Jest .each (github.com)