0

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.

Jason
  • 2,495
  • 4
  • 26
  • 37
  • Do you mean `expect(MessageBarFactory.addAlert).toHaveBeenCalledTimes(2);`? – jonrsharpe Oct 07 '21 at 14:47
  • You didn't update the error - did that not fix or at least _change_ it? – jonrsharpe Oct 07 '21 at 15:46
  • It did not. I have reformed the input code because it was much more convoluted because of injections. This is a MWE. – Jason Oct 07 '21 at 18:32
  • The message suggests you're passing MessageBarFactory, as in the original, not MessageBarFactory.addAlert (which _is_ a spy according to that output). – jonrsharpe Oct 07 '21 at 18:33

0 Answers0