test.each(table)(name, fn, timeout)
Also under the alias: it.each(table)(name, fn) and it.each`table`(name, fn)
Use test.each if you keep duplicating the same test with different data. test.each allows you to write the test once and pass data in.
test.each is available with two APIs:
1. test.each(table)(name, fn, timeout)
table:Arrayof Arrays with the arguments that are passed into the testfnfor 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]]
- Note If you pass in a 1D array of primitives, internally it will be mapped to a table i.e.
name:Stringthe title of the test block.- Generate unique test titles by positionally injecting parameters with
printfformatting:%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.
- Generate unique test titles by positionally injecting parameters with
fn:Functionthe test 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:
test.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
expect(a + b).toBe(expected);
});
2. test.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.
- First row of variable name column headings separated with
name:Stringthe title of the test, use$variableto inject test data into the test title from the tagged template expressions.- To inject nested object values use you can supply a keyPath i.e.
$variable.path.to.value
- To inject nested object values use you can supply a keyPath i.e.
fn:Functionthe test 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:
test.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added $b', ({a, b, expected}) => {
expect(a + b).toBe(expected);
});