简体   繁体   中英

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 .

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.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM