NagRock / ts-mockito

Mocking library for TypeScript
MIT License
974 stars 93 forks source link

Mocking the result of an async arrow function #155

Open jpletcher opened 5 years ago

jpletcher commented 5 years ago

I see that there are a bunch of issues around mocking arrow functions, and for me it works quite well, however I found that, if the result of a mocked function is itself a "mocked instance" then the function invocation times out.

I apologize for the complexity, but it would be great if you could wrap your head around this:

import { expect } from "chai";
import "mocha";
import { anything, instance, mock, verify, when } from "ts-mockito";

interface SomeInterface {
    someFooProperty: string;
}

interface InterfaceWithPromise {
    getPromise: (arg: string) => Promise<SomeInterface>;
}

describe("Promise Test", () => {

    const notMockedInstance: SomeInterface = {
        someFooProperty: "foo property",
    };
    let mockedInstance: SomeInterface;

    before(() => {

        const mockSomeInterface = mock<SomeInterface>();
        mockedInstance = instance(mockSomeInterface);

    });

    it("resolves the 'not mocked' result", async () => {

        const mockInterfaceWithPromise = mock<InterfaceWithPromise>();
        when(mockInterfaceWithPromise.getPromise(anything())).thenResolve(notMockedInstance);
        const testInstance = instance(mockInterfaceWithPromise);

        const result = await testInstance.getPromise("whatevz");
        console.log(result);
        expect(result).to.eq(notMockedInstance);
        // PASSES AS EXPECTED !
    });

    it("times out on the mocked result", async () => {

        const mockInterfaceWithPromise = mock<InterfaceWithPromise>();
        when(mockInterfaceWithPromise.getPromise(anything())).thenResolve(mockedInstance);
        const testInstance = instance(mockInterfaceWithPromise);

        const result = await testInstance.getPromise("whatevz");
        // THIS CODE IS NEVER REACHED / TEST TIMES OUT
        console.log(result);
        expect(result).to.eq(mockedInstance);

    });
});

Am I missing anything here?

hirikarate commented 5 years ago

Have a look at my workaround at this issue.