Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
edwinro opened this issue Sep 3, 2020 · 0 comments
Open

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

edwinro opened this issue Sep 3, 2020 · 0 comments

Comments

@edwinro
Copy link

edwinro commented Sep 3, 2020

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

  • Jest: 26.4.2
  • Typescript: 3.9.7
  • ts-mockito: 2.6.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant