Home > database >  Jest, mocking return from await, I see results in console, but expect still fails
Jest, mocking return from await, I see results in console, but expect still fails

Time:01-29

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.

CodePudding user response:

You are using an asynchronous function, but testing right away, before the promise is resolved. You need an async/await in your test, if you are using asynchronous calls, like your await in the main function.

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

    await fetchStuff(entity, service);

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

However, as per the comment on your question, the code may not be returning what you expect, so this change for async/await will not solve the problem on its own.

const fetchStuff = async (entity, service) => {
    entity = await service.get();
    console.log('entity is an expected result!', entity); 
    return entity;
}


it('should...', async () => {
    const expected = 'this will show up in console';
    const FakeService = jest.fn().mockResolvedValue(expected),

    const entity = await FakeService();
    expect(entity).toBe(expected) ;
});
  •  Tags:  
  • Related