Skip to content

Instantly share code, notes, and snippets.

@adrienjoly
Created March 23, 2023 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adrienjoly/2f8c48c4fde0ca235853131e400781ad to your computer and use it in GitHub Desktop.
Save adrienjoly/2f8c48c4fde0ca235853131e400781ad to your computer and use it in GitHub Desktop.
ways to use Jest's test.each
describe("ways to use Jest's test.each", () => {
test.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
expect(a + b).toBe(expected)
})
// => ✅ prints:
// ✓ .add(1, 1)
// ✓ .add(1, 2)
// ✓ .add(2, 1)
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)
})
// => ❌ does not replace $a by value
test.each([
{ a: 1, b: 1, expected: 2 },
{ a: 1, b: 2, expected: 3 },
{ a: 2, b: 1, expected: 3 },
])('.add(%o)', ({ a, b, expected }) => {
expect(a + b).toBe(expected)
})
// => ✅ prints:
// ✓ .add({ a: 1, b: 1, expected: 2 })
// ✓ .add({ a: 1, b: 2, expected: 3 })
// ✓ .add({ a: 2, b: 1, expected: 3 })
test.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({ a, b, expected }) => {
expect(a + b).toBe(expected)
})
// => ✅ prints:
// ✓ returns 2 when 1 is added to 1
// ✓ returns 3 when 1 is added to 2
// ✓ returns 3 when 2 is added to 1
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment