DEV Community

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

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

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⭐🙏

Top comments (0)