'Jest, mocking return from await, I see results in console, but expect still fails

I have a pretty simple example of a mock working, updating the value correctly, but my test still fails.

fetchStuff.js:

const fetchStuff = async (entity, service) => {
    entity = await service.get();
    console.log('entity is an expected result!', entity); // this consoles out the expected value correctly.
}

fetchStuff.spec.js:

it('should...', () => {
    const expected = 'this will show up in console';
    const service.get = jest.fn().mockImplementation(() => expected);
    let entity;

    fetchStuff(entity, service);

    expect(entity).toEqual(expected) // entity = 'undefined'
});

Every time, I see that console.log in the function is printing out the expected result, but some reason the expect(entity) is always undefined.

I've tried stuff like with flush-promise, I've tried removing the await. I've even seen the done(), technique, where we pass done in to it, ie it('should...', done => {...})

Not sure why I cannot get the correct expected, even tho the console is showing the expected result.

PS. I understand this is not respecting functional paradigm or pure functions. Please ignore that.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source