When writing tests with Jest you might want to write assertions that check expected function calls, your code might look a bit like this:

This certainly gets us part of the way, but by itself, this assertion is weak. Why is this?
Firstly we are not checking how many times our logic is calling the callback. This can be very important as the callback firing more than the expected amount could result in unexpected behavior in the code. Another consideration would be performance, maybe this callback firing more than the expected amount will still result in the expected behaviour, but it could result in logic being performed more than is required, what a waste of memory!
Lets’s see how we could do a bit better…

Ok nearly there! Now for the next missing puzzle piece – whilst we are now checking that the function gets called and how many times, we are still not checking parameters. Sometimes your function will not receive any parameters and this won’t be required, but too often I see tests that don’t check this even when there are, so let’s cover that.
Below is an example of an assertion we could add if we are expecting the parameter to be true:

We are now checking how many times the callback is called, and also what it is called with. For basic cases this will be enough, but let’s consider a more complex scenario.
Let’s say I expect my callback to be fired as so:
- First time – called with true
- Second time – called with false
- Second time – called with true
So often I have seen tests that would simply have an assertions for this type of scenario like so:

but this is brittle and let me explain why – these assertions are not specific enough in regards to order. This would pass no matter what order these parameters were detected, as long as both cases were detected for separate calls. How can we fix this?
|
1 2 3 4 5 6 |
it("calls the success callback", () => { expect(mockSuccessCallback).toHaveBeenCalledTimes(3); expect(mockSuccessCallback).toHaveBeenNthCalledWith(1, true); expect(mockSuccessCallback).toHaveBeenNthCalledWith(2, false); expect(mockSuccessCallback).toHaveBeenNthCalledWith(3, true); }); |
We now have a robust test that:
- checks how many times our function was called
- with what parameters it was called
- the order those parameters were called in