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

131
Vistas
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?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

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();
  });
});
over 4 years ago · Santiago Trujillo Denunciar

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();
  }));
over 4 years ago · Santiago Trujillo 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