timkindberg / jest-when

Jest support for mock argument-matched return values.
MIT License
734 stars 38 forks source link

mockReturnValue doesn't work when returning a function #34

Closed haines closed 5 years ago

haines commented 5 years ago

When configured to return a function, mockReturnValue calls that function and returns its return value, rather than returning the function itself. This is different to the behaviour of mockReturnValue on a plain jest.fn().

const returnValue = () => 'hello';

const mock1 = jest.fn();
mock1.mockReturnValue(returnValue);
expect(mock1('hi')).toBe(returnValue);

const mock2 = jest.fn();
when(mock2).calledWith('hi').mockReturnValue(returnValue);
expect(mock2('hi')).toBe(returnValue);

The first assertion succeeds but the second fails:

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

    Expected: [Function returnValue]
    Received: "hello"

    Difference:

      Comparing two different types of values. Expected function but received string.

The problem is here: https://github.com/timkindberg/jest-when/blob/25f0093ea8f845b11864ccc769a653980301f04d/src/when.js#L72

I think the simplest solution is to wrap the returnValue in a function here: https://github.com/timkindberg/jest-when/blob/25f0093ea8f845b11864ccc769a653980301f04d/src/when.js#L86-L87