码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-07-10 20:10:15      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:git   des   html   -name   class   down   The   tps   type   

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

 

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

标签:git   des   html   -name   class   down   The   tps   type   

原文地址:https://www.cnblogs.com/Answer1215/p/9291049.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!