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

154
Visualizações
Mocking base class in a unit test for Angular 2

I'm trying to write a unit test to see if the base class method gets called

Here is the base class

export abstract class Animal{
   protected eatFood() {
      console.log("EAT FOOD!")
   }
}

Here is the class I want to test

export class Monkey extends Animal {
   onHungry(){
      this.eatFood();
   }
}

Here is the test

class MockAnimal {
  public eatFood() { 
    console.log("EAT MOCKED FOOD!");
  }
}

describe('Monkey', () => {
  beforeEach(() => {

    TestBed.configureTestingModule({
       declarations:[Monkey],
       providers: [
         { provide: Animal, useClass: MockAnimal }
       ]
    }
  });

  it('eat food when hungry', fakeAsync(() => {
    let fixture = TestBed.createComponent(Monkey);
    spyOn(fixture, 'eatFood');
    fixture.componentInstance.onHungry();
    expect(fixture.eatFood).toHaveBeenCalled();
  }));
}

I can't get the unit test to run this MockAnimal class. Is this how to test it?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The TestBed is used to test components and as in a normal NgModule you define declarations, imports, providers, ... But what you want to test is a simple class. In the test you have to initialize it manually:

describe('Monkey', () => {
  it('eats if hungry', () => {
    const monkey = new Monkey();
    // spying will only work if 'eatFood' is public
    const eatFoodSpy = spyOn(monkey, 'eatFood');

    monkey.onHungry();

    expect(eatFoodSpy).toHaveBeenCalled();
  });
});
about 4 years ago · Santiago Trujillo Relatório

0

You can do this, that will mock your call.

  it('eat food when hungry', fakeAsync(() => {
    let fixture = TestBed.createComponent(Monkey);
    fixture.componentInstance['eatFood'] = jasmine.createSpy('eatFood');
    fixture.componentInstance.onHungry();
    expect(fixture.eatFood).toHaveBeenCalled();
  }));
about 4 years ago · Santiago Trujillo 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