Is there a reason I would prefer one method over the other? Here are some examples:
describe('some tests', () => {
[1, 2, 3].forEach(num => {
test(`${num}: test`, () => {
doSomeTestStuff(num)
})
})
// vs.
test.each([1, 2, 3])('%s: test', (num) => {
doSomeTestStuff(num)
})
})
It seems kind of difficult to read the test.each
syntax, especially when you can just do native javascript iteration to achieve what seems to be the same effect. Teardown/setup still happens the same way (from what I can tell).
Great question!
On the surface it would seem like the two are basically equivalent, but there are a few reasons why you may want to use .each
instead.
forEach
fails, it'll fail immediately and stop execution. This leaves you in the dark on whether the other tests in the forEach
passed or failed. With .each
it is basically writing a separate and distinct test for each item in your array.forEach
fails, it's not always obvious which item in the array caused the failure. In a .each
you automatically get context from the unique test name..each
you can use tagged template literals to handle multiple parameters easily, and as parameters grow the .each
can be very expressive and much more readable than an array with arbitrary values..each
creates a separate test for each item, the final report will make it seem like you wrote more tests than you actually have. Just a small thing that brings satisfaction when you look at the final output.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With