NagRock / ts-mockito

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

Verify if a function is called in a resolved promise #203

Open edwinro opened 3 years ago

edwinro commented 3 years ago

Summary

I want to test in a service class that a function is called following a resolved promise.

An error Expected "fooCall(anything())" to be called 1 time(s). But has been called 0 time(s). is thrown with the below setup.

I've looked in the docs and other issues, but haven't found a solution so far.

Data setup

I want to test the Bar service class, that uses a comm. layer CommLayer and performs a call fooCall to the UI Foo

        //Foo UI (simplified) - will be mocked
        class Foo {
            fooCall(s: String) {
            }
        }
        //CommLayer (simplified) - will be mocked
        class CommLayer {
            fetch(s: String) {
                return Promise.resolve(s);
            }
        }
        //Bar (simplified) - being tested
        class Bar {

            private commLayer: CommLayer;

            constructor(commLayer : CommLayer) {
                this.commLayer = commLayer;
            }

            request(foo: Foo) {
                   this.commLayer.fetch("result").then(value => {
                    console.log(value); //prints "result" - OK
                    foo.fooCall(value);
                })
            }
        }

Mocking

I am mocking the CommLayer and Foo:

        //given
        const MockedFoo: Foo = mock(Foo);
        const foo: Foo = instance(MockedFoo);
        const MockedCommLayer: CommLayer = mock(CommLayer);
        when(MockedCommLayer.fetch(anything())).thenResolve("result");
        const commLayer: CommLayer = instance(MockedCommLayer);

Tests

When testing the Bar request function, an error Expected "fooCall(anything())" to be called 1 time(s). But has been called 0 time(s) is thrown.

        //when
        const bar = new Bar(commLayer);
        bar.request(foo);

        //then
        verify(MockedFoo.fooCall(anything())).once(); // <---- Error: Expected "fooCall(anything())" to be called 1 time(s). But has been called 0 time(s).

When debugging in the IDE, I see that the resolved promise is executed. I notice console.log(value) displays 'result' in the logs.

Environment