How to use jest.each
14 August 2022 (Updated 14 August 2022)
Pass data as array:
function hasDuplicates(arr: any[]) {
return new Set(arr).size !== arr.length
}
describe('hasDuplicates', () => {
test.each([
[[2, 4, 4, 6], true],
[[2, 4, 6, 1, 6], true],
])(
'returns true if array has duplicates (e.g., %s)',
(input, expectedResult) => {
expect(hasDuplicates(input)).toEqual(expectedResult)
}
)
test.each([
[[2, 4, 6], false],
[[2, 4, 6, 1, 5], false],
])(
"returns false if array doesn't have duplicates (e.g., %s)",
(input, expectedResult) => {
expect(hasDuplicates(input)).toEqual(expectedResult)
}
)
})
Pass data as object:
test.each([
{a: 1, b: 1, expected: 2},
{a: 1, b: 2, expected: 3},
{a: 2, b: 1, expected: 3},
])('.add($a, $b)', ({a, b, expected}) => {
expect(a + b).toBe(expected);
});
Sources
Tagged:
JavaScript testing
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment