Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Jest what's the best way to loop through an array of inputs and expected outputs?

If I want to write a test for a calculator that adds things together. I might define my tests like this:

const tests = [
    {
      input: [1, 2],
      expected: 3,
    },
    {
      input: [2, 1],
      expected: 3,
    },
    {
      input: [3, 4],
      expected: 7,
    },
    {
      input: [2, 10],
      expected: 12,
    },
    {
      input: [2, 5],
      expected: 7,
    },
    ...
]

  tests.forEach((t) => {
    expect(add(t.input)).toEqual(t.expected)
  })

The problem is, if one of those tests fails, the error just says:

    Expected: "7"
    Received: "10"

      216 |   tests.forEach((t) => {
    > 217 |     expect(add(t.input)).toEqual(t.expected)
          |                                        ^
      218 |   })

From this, I can't tell if it was 3+4 that was calculated wrong, or 2+5 that was calculated wrong.

The alternative is instead of an array, define each one as its own test. However, that requires a lot more code, and you need to copy paste the expect statement everywhere.

So what is the best way to test complicated computation functions where you need to pass in many different permutations of input to be sure it is working?

like image 339
davidx1 Avatar asked Sep 18 '25 15:09

davidx1


1 Answers

You can use jest's test.each to define them as separate test cases:

test.each(tests)('add %j', ({ input, expected }) => {
  expect(add(input)).toEqual(expected)
})

but better yet you'd define the tests as following to take advantage of the printf formatting:

const tests = [
  [[1,2], 3],
  [[2,1],3],
  [[3,4],7],
  [[2,10],12],
  [[2,5],7]
]

test.each(tests)('add(%j) should equal %d', (input, expected) => {
  expect(add(input)).toEqual(expected)
})

working example

like image 112
Teneff Avatar answered Sep 20 '25 05:09

Teneff