Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

92
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda