DEV Community

Cover image for How to use jest test.each function
Adrian Matei for Codever

Posted on • Edited on • Originally published at codever.dev

2

How to use jest test.each function

Let's test with Jest the following isInfiniteDate function, which checks whether the given date is "infinite" in the given context:

export const isInfiniteDate = (input: string): boolean => {
    const maximumDatePossible = '9999-12-31';
    return new Date(input).getTime() === new Date(maximumDatePossible).getTime();
};
Enter fullscreen mode Exit fullscreen mode

For sure, we want to test different dates with the same expected result, either true or false

To avoid "duplication" of same test with different data, you can use test.each(table)(name, fn, timeout) function, to which you can pass an Array of Arrays with the arguments that are passed into the test fn for each row.

describe('isInfiniteDate > ', () => {
    test.each([
        [null, false],
        [undefined, false],
        ['AXON', false],
        ['2021-31-31', false],
        ['2021-12-12', false],
        ['9999-12-31', true],
    ])('given input date %p , it should return %p ', (input, expected) => {
        expect(isInfiniteDate(input)).toEqual(expected);
    });
});
Enter fullscreen mode Exit fullscreen mode
  • name is the String title of the test block - See the referenced link for the different formatting options
  • optionally, you can provide a timeout (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds.

This is the equivalent of @ParameterizedTest in Java


Reference -

https://jestjs.io/docs/api#testeachtablename-fn-timeout


Shared with ❤️ from Codever. Use 👉 copy to mine functionality to add it to your personal snippets collection.

Codever is open source on Github⭐🙏

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay