Thanks to visit codestin.com
Credit goes to github.com

Skip to content

test.each should perform string interpolation with object propertiesΒ #10394

@nth-commit

Description

@nth-commit

πŸš€ Feature Proposal

When giving an array of objects to the test.each overload that accepts an array, and not a template strings table, jest should interpolate the object's properties into the test name.

Motivation

The current interpolation of template strings works great, but it doesn't provide any hook for type-safety. This is problematic when scaling up to large and complex test cases, and in TypeScript, it allows any to sneak into your test functions. It also is more intuitive, it left me wondering for a while why a transformation to a type-safe version of a test wasn't causing interpolation of the test case.

Example

We can do something like this right now:

test.each`
  a    | b    | expectedResult
  ${1} | ${1} | ${2}
  ${2} | ${2} | ${4}
`('add($a, $b) === $expectedResult', ({ a, b, expectedResult }) => {
  expect(a + b).toEqual(expectedResult);
});

Which will output the test cases:
√ add(1, 1) === 2
√ add(2, 2) === 4

In order to achieve type-safety on the same test, I would make this transformation:

type AddExample = {
  a: number;
  b: number;
  expectedResult: number;
};

test.each<AddExample>([
  { a: 1, b: 1, expectedResult: 2 },
  { a: 2, b: 2, expectedResult: 4 },
])('add($a, $b) === $expectedResult', ({ a, b, expectedResult }) => {
  expect(a + b).toEqual(expectedResult);
});

Which I would expect should output the same test cases as above, but instead:
√ add($a, $b) === $expectedResult
√ add($a, $b) === $expectedResult

Pitch

It is isomorphic to functionality in the core library, but I believe it cannot be implemented as an extension.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions