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

91
Visualizações
Unit testing for backend and services methods calls with Jasmine

I started working with tests, more specifically with Jasmine, and I'm having some difficulty to test if the backend and some services methods are being called.

So basically I'm calling the forgotPassword method when the formulary is submitted and I was wondering how can I properly check if the API (apiSendPasswordResetLink) and the services methods (showLoader, showAlert and navigateTo) are being called as expected.

async forgotPassword() {
    try {
        console.log("1");
        this.loadingService.showLoader();
        console.log("2");
        await this.userService
            .apiSendPasswordResetLink(this.form.value['email'])
            .toPromise();

        console.log("3");
        this.utilitiesService.showAlert(`We've emailed you a link to reset your password. Please check your mail box and spam.`);

        console.log("4");
        delay(1500);
        this.navigationService.navigateTo('/login/auth');
        console.log('5')
    } catch (err) {
        this.utilitiesService.showAlert(err);
    } finally {
        this.loadingService.hideLoader();
    }
}

The test:

it('should submit email to reset password after submitting formulary', () => {
    component.form.setValue({
      email: 'test@test.io',
    });

    const loadingService = TestBed.inject(LoaderService);
    const userService = TestBed.inject(UserService);
    const utilitiesService = TestBed.inject(UtilitiesService);
    const navigationService = TestBed.inject(NavigationService);

    fixture.detectChanges();

    const button = fixture.debugElement.nativeElement.querySelector('#button');

    spyOn(component, 'forgotPassword').and.callThrough();
    spyOn(loadingService, 'showLoader');
    spyOn(userService, 'apiUserSendPasswordResetLink');
    spyOn(utilitiesService, 'showAlert');
    spyOn(navigationService, 'navigateTo');

    // Submitting form
    fixture.debugElement
      .query(By.css('form'))
      .triggerEventHandler('ngSubmit', null);

    expect(component.form.valid).toEqual(true);
    expect(button.disabled).toBeFalsy();
    expect(component.forgotPassword).toHaveBeenCalled();
    expect(loadingService.showLoader).toHaveBeenCalled();
    expect(userService.apiUserSendPasswordResetLinkGet).toHaveBeenCalled();
    expect(utilitiesService.showAlert).toHaveBeenCalled();
    expect(navigationService.navigateTo).toHaveBeenCalled();
  });

Every time I run and / or debug the test, I have the error

Expected spy navigateTo to have been called.

But the console never prints "3", which means showAlert is also not being called and I should also have the same error regarding showAlert spy to be called, but I don't.

I don't know if this problem has to do if the await call to the API or something else. I would like to know how can I fix it, so all the test can pass as expected.

Thank you!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When adding a spy on UserService#apiUserSendPasswordResetLink, without any spy strategy, it defaults to doing nothing. However, in your forgotPassword method, you are chaining the response of the call to a Promise wrapper and awaiting the resolution. Since apiUserSendPasswordResetLink is not invoked, I'm guessing that the promise is never resolved and the test gets stuck.

One simple way to resolve the issue is to add a strategy to the spy so that it returns a value:

spyOn(userService, 'apiUserSendPasswordResetLink').and.returnValue('whatever');
about 4 years ago · Juan Pablo Isaza Relatório
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