describe.each(table)(name, fn, timeout)

Use describe.each if you keep duplicating the same test suites with different data. describe.each allows you to write the test suite once and pass data in.

describe.each is available with two APIs:

1. describe.each(table)(name, fn, timeout)

  • table: Array of Arrays with the arguments that are passed into the fn for each row.
    • Note If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. [1, 2, 3] -> [[1], [2], [3]]
  • name: String the title of the test suite.
    • Generate unique test titles by positionally injecting parameters with printf formatting:
      • %p - pretty-format.
      • %s- String.
      • %d- Number.
      • %i - Integer.
      • %f - Floating point value.
      • %j - JSON.
      • %o - Object.
      • %# - Index of the test case.
      • %% - single percent sign (‘%’). This does not consume an argument.
  • fn: Function the suite of tests to be ran, this is the function that will receive the parameters in each row as function arguments.
  • Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait for each row before aborting. Note: The default timeout is 5 seconds.

Example:

describe.each([ [1, 1, 2], [1, 2, 3], [2, 1, 3], ])('.add(%i, %i)', (a, b, expected) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected); }); test(`returned value not be greater than ${expected}`, () => { expect(a + b).not.toBeGreaterThan(expected); }); test(`returned value not be less than ${expected}`, () => { expect(a + b).not.toBeLessThan(expected); }); });

2. describe.each`table`(name, fn, timeout)

  • table: Tagged Template Literal
    • First row of variable name column headings separated with |
    • One or more subsequent rows of data supplied as template literal expressions using ${value} syntax.
  • name: String the title of the test suite, use $variable to inject test data into the suite title from the tagged template expressions.
    • To inject nested object values use you can supply a keyPath i.e. $variable.path.to.value
  • fn: Function the suite of tests to be ran, this is the function that will receive the test data object.
  • Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait for each row before aborting. Note: The default timeout is 5 seconds.

Example:

describe.each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} `('$a + $b', ({a, b, expected}) => { test(`returns ${expected}`, () => { expect(a + b).toBe(expected); }); test(`returned value not be greater than ${expected}`, () => { expect(a + b).not.toBeGreaterThan(expected); }); test(`returned value not be less than ${expected}`, () => { expect(a + b).not.toBeLessThan(expected); }); });