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β­πŸ™

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

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

Okay