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

Multiple stubs, count wrong? #387

Closed
gonzalonaveira opened this issue Oct 15, 2018 · 1 comment
Closed

Multiple stubs, count wrong? #387

gonzalonaveira opened this issue Oct 15, 2018 · 1 comment

Comments

@gonzalonaveira
Copy link

Description

I'm doing multiple stubs on an object, the stubs seems to work but when I check the call count it's zero.
In the example I provide i want to verify on the log function that it was called with the proper parameters.

After debugging it I verified that the parameters are correct, I also tried with td.matchers.anything().

Environment

-Node 8.11.1
-npm 6.4.1
-testdouble 3.8.2

Example Repo

https://github.com/gonzalon/node-ut

@searls
Copy link
Member

searls commented Oct 15, 2018

Your issue is that your test executes synchronously and exits immediately, but your subject is asynchronous and doesn't exit until at least two additional ticks of the event loop.

Annotated source:

    // You're good so far
    math.sum(a, b).then( (r) => {
        // All of this will execute in the next tick (after the test has exited)

        math.log(r);

        // Therefore, at test-time, this call won't have happened yet:
        math.substract(a, b).then( (rs) => {
            // And this is now scheduled at least one tick later
            math.log(rs);

            const body = {sum: r, substract: rs};

            // To test this, you need some kind of mechanism (a callback,
            // a returned promise, etc.) to continue execution of the test
            res.status(200).send(body);
        })
    });

Options:

  1. Refactor the subject to not be fire-and-forget, which would be good form as that's as unobservable as a private anonymous function. For how to write async tests in Jest I'll have to refer you to their docs

  2. Configure a fake promise implementation which will execute synchronously for you. I wouldn't recommend this as you might find other bugs sneak in due to synchronous execution of code that will always be async in prod. docs

@searls searls closed this as completed Oct 15, 2018
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

2 participants