Recently I came across a scenario where I had to make sure that a proper callback function was being passed to a function I was testing with Jest.
In my test, I wanted to test that doSomething is getting called with correct arguments.
The first argument is easy to test for as it’s a string, the second argument isn’t as straightforward.
Given we have utility.doSomething mocked in our Jest test, it might seem like we can test it like this:
However, that will not work because the callback is bound, so it won’t match the callback function definition.
We could take a simpler approach and just match for any function:
However, this approach doesn’t really test that a correct callback is passed.
One good way I’ve found to test this scenario is to create an instance of the callback function itself, and check to see that the argument passed to the stubbed doSomething function is an instanceof the instance we just created.
Object.create(TestComponent.prototype.callback.prototype) instanceof utility.doSomething.mock.calls