mardi 25 août 2020

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?

Aucun commentaire:

Enregistrer un commentaire