在Jest中,循环遍历一系列输入和预期输出的最佳方法是什么? [英] In Jest what's the best way to loop through an array of inputs and expected outputs?

查看:807
本文介绍了在Jest中,循环遍历一系列输入和预期输出的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想为将所有内容加在一起的计算器编写测试.我可以这样定义测试:

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

由此,我无法确定是3 + 4的计算错误还是2 + 5的计算错误.

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

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

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?

推荐答案

您可以使用jest的

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

但更好的是,您需要定义tests以便利用printf格式:

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

工作示例

这篇关于在Jest中,循环遍历一系列输入和预期输出的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆