marchaos / jest-mock-extended

Type safe mocking extensions for Jest https://www.npmjs.com/package/jest-mock-extended
MIT License
836 stars 57 forks source link

Test hangs when async method returns a mock #2

Closed eddiemf closed 4 years ago

eddiemf commented 4 years ago

Hello there, I've found a problem that is keeping me from using this very helpful package.

I have a use case very similar to the structure of this example code, where my test subject receives an async factory as dependency which is called inside of it to do stuff:

it('should work', async () => {
  interface Engine {
    start: () => Promise<void>;
  }

  const makeCar = async ({ makeEngine }) => {
    const engine = await makeEngine(); // code hangs here
    return {
      turnOn: async () => {
        await engine.start();
        return true;
      },
    };
  };

  const engineMock = mock<Engine>();
  const car = await makeCar({ makeEngine: async () => engineMock });
  await car.turnOn();
  expect(engineMock.start).toHaveBeenCalled();
});

The problem here is that the code hangs on await makeEngine() for some reason.

If I change the factory to not be async like this const car = await makeCar({ makeEngine: () => engineMock }); it will work perfectly. Also if I change engineMock for a simple mock object like { start: jest.fn() } it will also work, which leads me to think that the problem is in this library.

Do you have any idea on what could be causing this issue?

Thanks!

marchaos commented 4 years ago

Hey. I'll take a look at fixing this. I'll see if I can get a test case to see it fail first.

iiSergey commented 4 years ago

I encountered this problem also. I researched it and found one resolve. If some object return as promise then for this object checked property 'then'. If 'then' has function then this function become next a chain of promise. For break this chain need set property 'then' to undefined. I created pull request https://github.com/marchaos/jest-mock-extended/pull/7

marchaos commented 4 years ago

This should be fixed and released with version 1.0.6