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

206
Visualizações
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 Respostas
Responde à pergunta

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 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