0

I know the benefits of using test.each over forEach and would like to convert some of my tests. The problem: I look around and all I see is very unclean ways of writing the same.

Is there a way to use test.each in a way

    const testCases = [
      { value: true, anothervalue: 12 },
      { value: false, anotherValue: 13 },
    ]

    testCases.forEach(({ value, anotherValue }) => {
      it(`should set ${value} to ${!!anotherValue}`, async () => {
        await doSomething(value)

        expect(doSomething).toEqual(`something${anotherValue}`)
        )
    
      })

Is there a way to implement something similar using test.each that is also very readable and clean?

CaitlynCodr
  • 238
  • 1
  • 15
  • _"the benefits of using `test.each` over `forEach`"_ - what are they? IMO what you've posted is perfectly fine, and is portable between test frameworks. (E.g. I just read https://stackoverflow.com/a/65908574/3001761 - three of the four bullets are wrong and the 4th is a matter of opinion!) – jonrsharpe May 04 '22 at 17:14
  • Hi! Thanks for your quick response. I see! The benefits I described came from that thread as well. I just tested it and indeed see now that the first bullet is wrong. Thanks :) Do you see any benefit at all in using `test.each` over `forEach`? – CaitlynCodr May 04 '22 at 17:26
  • I don't think `test.each` does anything you can't easily do yourself, and the template string syntax can be [downright surprising](https://stackoverflow.com/q/70804721/3001761). My preference is for the vanilla JS version because you can still create unique test names (as you show) with template strings, and that way your IDE/editor can help you get names right (e.g. `'.add($a, $b)'` can't be checked for whether those names are correct, whereas `\`.add(${a}, ${b})\`` can). – jonrsharpe May 04 '22 at 17:30
  • I've added my own answer there: https://stackoverflow.com/a/72117404/3001761 – jonrsharpe May 04 '22 at 17:50

0 Answers0