【问题标题】:Mocking base class unit test angular 2模拟基类单元测试角度2
【发布时间】:2017-09-04 22:38:52
【问题描述】:

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

这是基类

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

我们将不胜感激。

谢谢

【问题讨论】:

  • 窥探fixture.componentInstance,而不是fixture。夹具没有方法eatFood
  • 谢谢@peeskillet 那没用。如何在 MockAnimal 类而不是实际的 Animal 类中执行eatFood?

标签: javascript unit-testing angular karma-jasmine


【解决方案1】:

你可以这样做,它会模拟你的调用。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    相关资源
    最近更新 更多