es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

Cómo ejecutar casos de prueba unitarios para mensajes tipo toast en un servicio de Angular?

Estoy trabajando con una aplicación basada en Angular 12. Tengo un servicio llamado servicio de notificación que se encarga de los mensajes de tostadas de la biblioteca ngx-toastr.

Así es como se ve ese servicio:

export class NotificationService {
  constructor(private toastr: ToastrService) {}

  showSuccess(message: string = 'Éxito ', note: string = ''): void {
    this.toastr.success(message, note);
  }

  showError(message: string = 'Error ', note: string = 'Inténtalo de nuevo'): void {
    this.toastr.error(message, note, {
      timeOut: 3000,
    });
  }
}

Los métodos del servicio funcionan bien, pero cuando intento implementar pruebas para ellos, obtengo el siguiente error:

La prueba del método "showSuccess" del servicio de Notificación FALLÓ

Error: <spyOn>: no se pudo encontrar un objeto para espiar en el método success()

Estas son las pruebas:

describe('NotificationService', () => {
  let notificationService: NotificationService,
    httpTestingController: HttpTestingController,
    toastrService: ToastrService,
    notificationServiceSpy: any;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [CommonModule, HttpClientTestingModule, ToastrModule.forRoot()],
      declarations: [],
      providers: [{ provide: ToastrService, useValue: toastrService }],
    }).compileComponents();
    notificationService = TestBed.inject(NotificationService);
    httpTestingController = TestBed.inject(HttpTestingController);
    toastrService = TestBed.inject(ToastrService);
  });

  it('debería ser creado', () => {
    expect(notificationService).toBeTruthy();
  });

  it('debería probar el método "showSuccess"', () => {
    spyOn(toastrService, 'success').and.callThrough();
  });

  afterEach(() => {
    httpTestingController.verify();
  });
});

Se agradece cualquier ayuda. ¡Gracias!

Tags:  , , , ,

Answer

  1. Avatar for davy.ai

    Solución:

    El problema aquí es que necesitas crear un objeto espía para toastrService antes de poder llamar al método showSuccess(). En la implementación actual, estás intentando espiar en el método success() de toastrService después de haber llamado al método showSuccess().

    Para solucionar este problema, debes crear el objeto espía antes de llamar al método showSuccess(). Aquí tienes el caso de prueba actualizado para el método showSuccess():

    it('should test "showSuccess" method', () => {
        spyOn(toastrService, 'success').and.callThrough();
        notificationService.showSuccess();
        expect(toastrService.success).toHaveBeenCalled();
    });
    

    En este caso de prueba actualizado, primero estás creando un objeto espía para el método success() usando el método spyOn() de Jasmine. Luego estás llamando al método showSuccess() de notificationService y finalmente verificando que se haya llamado al método success() de toastrService usando el método toHaveBeenCalled() de Jasmine.

    Esto debería solucionar el error y tu caso de prueba debería pasar ahora.

Comments are closed.