Mocking base class unit test angular 2

时间:2017-04-10 01:31:16

标签: javascript unit-testing angular karma-jasmine

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!")l
   }
}

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 cant get the unit test to run this MockAnimal class. Is this the best way to test it?

Sorry if this a noob question, i'm just starting out with angular 2

Any help will be appreciated.

Thank you

1 个答案:

答案 0 :(得分:0)

您可以执行此操作,这将模拟您的通话。

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