Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
Jasmine on AngularJS: ensuring number of calls to a spied method

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.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda