Search code examples
javascriptnode.jstypescripttestingjestjs

Testing the function type returned from another function


I have a function which returns another function:

    const returnedFunction = () => {}

    const returnFunction = () => {
        const function = returnedFunction();

        // Do stuff

        return function;
    }

I want to test the type of function returned from returnFunction is of type returnedFunction. Jest seems to pick it up in the response:

    expect(received).toBe(expected) // Object.is equality

    Expected: "[Function returnedFunction]"
    Received: [Function returnedFunction]

but I can't work out how to match them up.


Solution

  • Functions are compared by reference, so if you construct the function in your returnedFunction and in your tests, even if they look the same they will not be considered equal.

    You should introduce some way of sharing the reference between your tests and your code. For instance,

    // Note that sharedFn can now be used in your test for comparison
    const sharedFn = () => {};
    const returnedFunction = () => { return sharedFn; };
    
    ...
    
    const received = returnFunction();
    expec(received).toBe(sharedFn);