繁体   English   中英

模拟基类单元测试角度2

[英]Mocking base class unit test angular 2

我正在尝试编写一个单元测试来查看基类方法是否被调用

这是基类

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

这是我要测试的课程

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

这是测试

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();
  }));
}

我无法通过单元测试来运行这个MockAnimal类。 这是测试它的最佳方法吗?

对不起,如果这是一个菜鸟问题,我刚刚开始使用角度2

任何帮助将不胜感激。

谢谢

你可以这样做,这将模拟你的电话。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM