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

205
Vistas
Angular Karma JUnit test - SpyOn does not work within private method

I try to test my component, I know the component works fine but my test gives error since Angular version has been updated to 12.

This is my component:

ngOnInit() {
    if (versonA) {
        this.doThis();
    } else {
        this.doThat();
    }
}

private doThis() {
this.myService.confirm({
        message: message,
        accept: () => {
            this.doAcceptLogic();
        }, reject: () => {
            console.log('reject')
            this.doRejectLogic();
        }
    });
}

And this is my test:

beforeEach(async () => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.autoDetectChanges();
    spyOn(TestBed.get(MyService), 'confirm').and.callFake((params: Confirmation) => {
        params.reject();
    });
    await fixture.whenStable();
});

And still, this spyOn does not seem to work. I put a lot of console logs into my code and the doThis() method still get called but the log within my confirm method ('reject') does not get written to the console. I cannot see why.

As I change the doThis() method to public and call it directy from my test as component.doThis(), then it runs to into the mocked myService.

Can anybody explain my why?

Thanks a lot!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  1. You can call private methods in your spec either by casting to any
(component as any).doThis();

or using []

component['doThis']();
  1. You call fixture.autoDetectChanges() it may call ngOnInit which is calling doThis before even you created the spy.
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