我有一个组件,在ngoninit函数内部有一个setTimeout函数。为了编写单元测试用例,我使用Tick和FakeAsync快速转发设置超时。但是,它不会被执行,而这反过来又不会调用其他函数closeAlert()。
  
  
   组件代码:
  
  export class BannerComponent implements OnInit {
  @Input()errorData: any;
  @Input()callback: any;
  @Input()autoHide: boolean;
  constructor() { }
  ngOnInit() {
    if (this.autoHide) {
      setTimeout
        (() => {
          this.closeAlert();
        }, 500);
    }
  }
  closeAlert() {
    this.errorData = null;
    if (this.callback) {
      this.callback();
    }
  };
}
  
   规格文件:
  
  describe('BannerComponent', () => {
  let component: BannerComponent;
  let fixture: ComponentFixture<BannerComponent>;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ BannerComponent ]
    })
    .compileComponents();
  }));
  beforeEach(async() => {
    fixture = TestBed.createComponent(BannerComponent);
    component = fixture.componentInstance;
    component.ngOnInit();
    fixture.detectChanges();
  });
  it("banner should hide after 500ms", fakeAsync(() => {
    component.errorData = {
      _statusMessage: "New alert banner",
      _statusCode: '200',
    };
    component.callback = null;;
    component.autoHide = true;
    tick(600);
    fixture.detectChanges()
    fixture.whenStable().then(() => {
      let banner = fixture.debugElement.query(By.css('.success'));
      expect(banner).toBe(null)
    })
  }));
});
  
   HTML代码:
  
  <div class="success">
    <p>{{errorData._statusMessage}}</p>
</div>