Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jest's test.each vs. looping with forEach

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).

like image 623
Mike Avatar asked Jul 23 '19 20:07

Mike


1 Answers

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.

  • If an expectation in a 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.
  • If an expectation in a 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.
  • With .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.
  • Since, as I said before, .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.
like image 123
Scott Hampton Avatar answered Sep 20 '22 17:09

Scott Hampton