【问题标题】:In Jest what's the best way to loop through an array of inputs and expected outputs?在 Jest 中,循环输入和预期输出数组的最佳方法是什么?
【发布时间】:2020-08-26 05:08:55
【问题描述】:

如果我想为计算器编写一个将事物加在一起的测试。我可能会这样定义我的测试:

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)
  })

问题是,如果其中一项测试失败,错误只会显示:

    Expected: "7"
    Received: "10"

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

由此,我分不清是3+4算错了,还是2+5算错了。

替代方法是代替数组,将每个定义为自己的测试。但是,这需要更多代码,并且您需要将expect 语句复制粘贴到任何地方。

那么测试复杂计算函数的最佳方法是什么?您需要传入许多不同的输入排列以确保其正常工作?

【问题讨论】:

    标签: unit-testing testing jestjs automated-tests


    【解决方案1】:

    您可以使用 jest 的 test.each 将它们定义为单独的测试用例:

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

    但更好的是,您可以将 tests 定义如下以利用 printf 格式:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-29
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      相关资源
      最近更新 更多