I am using these two separate assertions in a Jasmine unit test.
expect(spyFunction).toHaveBeenCalledWith(expectedArgument);
expect(spyFunction).toHaveBeenCalledTimes(expectedCount);
If I understand correctly these will confirm the following.
expectedArgument
at least once, andexpectedCount
times.What I want to do is confirm that the function is called with expectedArgument
exactly expectedCount
times. In other words I want to count only the number of calls in which the argument matches.
I realize I could do my own counting with a fake...
var callCount = 0;
spyOn(myInstance, 'myFunction').and.callFake(arg => {
if (arg === expectedArgument) {
callCount++;
}
});
...
expect(callCount).toEqual(expectedCount);
...but that does not have the readability of the previous syntax and feels like reinventing the wheel. I have not used Jasmine all that much so I wonder if I'm missing something.
Is there a way to make my assertion using built-in Jasmine matchers? Alternatively, is there another way to obtain similarly readable syntax?
You can get more detailed information from the spy using calls
. You can look at each call and its arguments like this:
expect(spyFunction.calls.count()).toBe(2)
expect(spyFunction.calls.argsFor(0)).toEqual(/* args for 1st call */)
expect(spyFunction.calls.argsFor(1)).toEqual(/* args for 2nd call */)
See Jasmine docs for details.