typescriptunit-testingmockingts-mockito

How to mock a method using ts-mockito?


I want create a mocked object of a class via ts-mockito@2.5.0 but I am unable to set it up properly.

Here's contrived test case:

import {expect} from "chai";
import {
    mock,
    when,
} from "ts-mockito";

class MockMe {
    public doStuff(): string {
        return "I AM THE ORIGINAL VALUE";
    }
}

describe("ts-mockito weirdness", async () => {
    it("should create a mock with specific return values", async () => {
        const mocked = mock(MockMe);

        await when(mocked.doStuff()).thenReturn("I AM MOCKED");

        const actualReturnValue = mocked.doStuff();

        expect(actualReturnValue).to.eq("I AM MOCKED");
    });
});

As the test-case implies, I expect the return value of "I AM MOCKED" from my mock.

But I am getting a ts-mockito-specifc object instead, containing properties like: methodStubCollection, matchers, mocker, and name.

Screenshot of unexpected response from ts-mockito

How am I supposed to setup the mock that it works as intended?


Sidenote: This test-case is only to showcase the weird behavior I am experiencing. It's not my actual test. I want to use a mock in a unit-test for a different service.)


Solution

  • You are missing the instance call due to technical limitation of TypeScript.

    import {
        instance,
        mock,
        when,
    } from "ts-mockito";
    
    const mockitoMock = mock(MockMe);
    const actualInstanceOfMock = instance(mocked).doStuff();
    actualInstanceOfMock.doStuff() // will return your mocked value