Home > Software design >  How to test a function that returns an arrow function with Jest?
How to test a function that returns an arrow function with Jest?

Time:05-03

I have a function like this:

export const myFunc = (a, b ,callBack) => {
    const timer = setTimeout(() => {
        callBack(a b);
    }, 10);
    return () => clearTimeout(timer);
};

I'm able to test the callback function just fine by doing this:

jest.useFakeTimers();

describe('myFunc', () => {
    const callBack = jest.fn();

    it('runs myFunc', () => {
        myFunc(1, 2, callBack);
        jest.runAllTimers();

        expect(callBack).toHaveBeenCalledWith(3);
    });

However, the last line return () => clearTimeout(timer) is never tested somehow. Jest report just says this line function not covered and statement not covered. Can anyone please tell me a way to cover this line without using any other external testing library like enzyme?

CodePudding user response:

The function isn't called, so it's not covered.

Another test would be:

    let cleanup = myFunc(1, 2, callBack);
    cleanup()
    jest.runAllTimers();
    expect(callBack).not.toHaveBeenCalled();
  • Related