From the Jest (v29.7) API docs for test.each
:
If you pass in a 1D array of primitives, internally it will be mapped to a table i.e.
[1, 2, 3] -> [[1], [2], [3]]
If your test inputs sometimes have a mix of arrays and non-arrays and you
try to pass in ["a", "b" ["c"]]
sometimes and [["a"], "b", "c"]
other
times, Jest might wrap all of your elements in an array to make them table
rows, but on the other hand it might instead see one of your elements is an
array, assume that means it’s already formatted as a row, and then assume
the rest of your elements are formatted as rows even if they aren’t; this
results in… surprising behaviour.
A solution? Wrap all of your elements in arrays yourself so you don’t have
to rely on Jest’s guess. But [[1], 2, 3]
is cleaner and easier to read
than [[[1]], [2], [3]]
. That’s where toTable
comes in:
toTable([[1], 2, 3])
returns [[[1]], [2], [3]]
.
Consider using toTable
any time you have a mix of arrays and non-arrays in
your test.each
inputs for consistent behaviour from Jest.
Encloses each element in
xs
in an array for passing into Jest’stest.each
. If somex
is already[...]
, it will become[[...]]
.