I have a service called MessageBarFactory
, with a void
method called addAlert()
. I have a unit test where I don't want that method to ever be called, so I just spy on it as follows:
spyOn(MessageBarFactory, 'addAlert'); // And do nothing
In the branch of the code base that I am testing, there are two consecutive calls to this method:
.
.
.
MessageBarFactory.addAlert('Patient ' + $scope.patientIn.name.firstName + ....);
MessageBarFactory.addAlert('An error occurred attempting to load the patient details ....);
.
.
.
In order to ensure that that branch is being followed, I am testing to see if that method has been "called" twice:
expect(MessageBarFactory.addAlert).toHaveBeenCalledTimes(2);
But I get a message that also involves some other spies of mine in other methods of the same service, such as clearAlertByName
:
Error: <toHaveBeenCalledTimes> : Expected a spy, but got Object({ alerts: [ ], addAlert: spy on addAlert, closeAlert: Function, clearAll: Function, clearAlertByName: spy on clearAlertByName, clearAllExceptForWidget: Function, clearAlertByNameByType: Function }).
.
.
.
Now, of course, I could be doing something like:
let counter = 0;
spyOn(MessageBarFactory, 'addAlert').and.callFake(
function(){
counter++;
}
);
.
.
.
expect(counter).toEqual(2);
But this is a bit unnatural and requires that you also put in a fake function, which increases runtime overhead for the spy (not the most important point within a testing context, but still).
I'm looking to see if I am thinking about this wrong: is toHaveBeenCalledWithTimes()
incompatible with spied on methods? I would think that this is exactly why you might want to spy on a method. What am I missing here? For reference, I am using Jasmine 3.1.0 and unfortunately this is not negotiable for this project, which has a big backwards compatibility focus.