[Jest] Write data driven tests in Jest with test.each

通过JUnit 23版本新增的test.each方法,可以将多个单元测试案例整合为单一的数据驱动测试,简化测试代码并提高维护效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Often, we end up creating multiple unit tests for the same unit of code to make sure it behaves as expected with varied input. This is a good practice, but it can be a little tedious to create what is essentially the same test multiple times. We copy a test, paste it and update the variables that matter. Maybe we do that several times. Then, if we need to update our tests, we update each copy of the test. The good news is, starting with version 23 of Jest, there is built-in support for creating data-driven tests. In this lesson we'll take a handful of unit tests and reduce them down to a single, data-driven test with the new test.each method in Jest. We'll also look at the alternate version of test.each that lets us use a tagged template literal to describe the data for our test.

Additional info:

In the Jest docs: https://facebook.github.io/jest/docs/en/api.html#testeachtable-name-fn

Jest cheatsheet: https://github.com/sapegin/jest-cheat-sheet#data-driven-tests-jest-23

 

describe('isPalindrome - each', () => {
  const data = [
    ['Racecar', true],
    ['Typewriter', false],
    ['rotor', true],
    ['kayak', true],
    ['Step on no pets', true]
  ];
  test.each(data)('isPalindrome(%s) --- %s', (input, expected) => {

    const result = isPalindrome(input);
    expect(result).toBe(expected)
  })
})

describe('isPalindrome - each template literal', () => {
  test.each`
  input           | expected
  ${'Racecar'}    | ${true}
  ${'Typewriter'} | ${false}
  ${'rotor'}      | ${true}
  `('isPalindrome("$input") - $expected', ({ input, expected }) => {
    const result = isPalindrome(input)
    expect(result).toBe(expected)
  })
})

 

转载于:https://www.cnblogs.com/Answer1215/p/9291049.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值