Search code examples
jestjsts-jest

How to pass in the done() parameter on an async jest test.each case


I'm trying write a jest test case that tests an async method, I want to pass in the done() parameter so jest waits for it to be fired before it ends the test, however, I'm not sure where to put it.

Any ideas?

const testcases = [
        [
            'Crew',
            [1,2,3],
            Enum.Level1
        ],
        [
            'Staff',
            [4,5,6],
            Enum.Level2
        ]
    ];
test.each(testcases )(
        'Should be able to load differing cases %p',
        (
            typeName: string,
            initalVals: string[],
            type: LevelType
        ) => {
            // some call that updates mobx store state

            when(
                () => mobxstoreProperty.length == initalVals.length,
                () => {
                    // my assertions

                    done();
                }
            );
        }
    );

For a single jest test I can do this:

test('my single test', done => {
  // some call that updates mobx store state

     when(
       () => mobxstoreProperty.length == initalVals.length,
       () => {
         // my assertions
         done();
       }
    );
});

Just unsure how to do it for when I use the test.each method.


Solution

  • I use named parameters and I can add the done() method as the last function parameter. For example like so:

    const testcases: {
        typeName: string;
        initalVals: string[],
        type: LevelType
    }[] = [
        {
            typeName: 'Crew',
            initalVals: [1,2,3],
            type: Enum.Level1
        },
        {
            typeName: 'Staff',
            initalVals: [4,5,6],
            type: Enum.Level2
        },
    ];
    test.each(testcases)(
        'Should be able to load differing cases %p',
        // Must use `any` for `done`, as TypeScript infers the wrong type:
        ({typeName, initalVals, type}, done: any) => {
            // some call that updates mobx store state
            when(
                () => mobxstoreProperty.length == initalVals.length,
                () => {
                    // my assertions
    
                    done();
                }
            );
        }
    );
    

    I haven't tested if you can just add the done() method as last parameters with array arguments, but maybe that works, too.