Jest: Support shallow arrays in jest-each

Created on 29 May 2018  路  5Comments  路  Source: facebook/jest

I expected I could write this:

test.each(['red', 'green', 'bean'])("The word %s contains the letter 'e'", word => {
  expect(/e/.test(word)).toBe(true);
});

But it lead to very confusing test titles and test failures:

screen shot 2018-05-29 at 2 50 19 pm

I ended up doing something like this, and it worked.

test.each(['red', 'green', 'bean'].map(word => [word]))(
  "The word %s contains the letter 'e'",
  word => {
    expect(/e/.test(word)).toBe(true);
  },
);

At the very least, it would be nice to error if the values in the table are not arrays.

@mattphillips

Most helpful comment

I think option two is best, since I would imagine it's pretty common to want to make the same assertion about an array of values, and having to manually convert the array to a table is kinda gross.

All 5 comments

Hey @captbaritone the array needs to represent a table:

test.each([
  [arg1, arg2, arg3], // row1
  [arg1, arg2, arg3], // row2
])

We could add a check here https://github.com/facebook/jest/blob/master/packages/jest-each/src/bind.js#L24 to make sure the inner row array is actually an array. What do you think?

Yeah, I figured that out eventually, and it makes sense. I would say we should check if it's an array and either:

  1. Throw a helpful error.
  2. Convert it to an array of length one automatically.

I'm not torn either way, in fact I think I'm leaning towards options 2.

@SimenB @thymikee what do you guys think?

I think option two is best, since I would imagine it's pretty common to want to make the same assertion about an array of values, and having to manually convert the array to a table is kinda gross.

Cool I'll send a PR :)

Was this page helpful?
0 / 5 - 0 ratings