How to loop through dynamic test cases with Jest?

Sometimes, we want to loop through dynamic test cases with Jest.

In this article, we’ll look at how to loop through dynamic test cases with Jest.

How to loop through dynamic test cases with Jest?

To loop through dynamic test cases with Jest, we can use the test.each method.

For instance, we write

test.each([
  [1, 1, 2],
  [1, 2, 3],
  [2, 1, 3]
])(
  '.add(%i, %i)',
  (a, b, expected) => {
    expect(a + b).toBe(expected);
  },
);

to call test.each with a nested array of values.

Then we call the returned function with a test name template string and the test callback.

a, b and expected are the entries from the nested array entry of the array we pass into each.

And then we can use the parameters for the tests.

Conclusion

To loop through dynamic test cases with Jest, we can use the test.each method.