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:Arrayof Arrays with the arguments that are passed into thefnfor 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 suite.- 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 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.
- First row of variable name column headings separated with
name:Stringthe title of the test suite, use$variableto 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
- To inject nested object values use you can supply a keyPath i.e.
fn:Functionthe 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);
});
});