2016-10-17 37 views
0
@Input() 
    public set isRunning(value: boolean) { 
     if (!value) { 
      this.cancelTimeout(); 
      this.isDelayedRunning = false; 
      return; 
     } 

     if (this.currentTimeout) { 
      return; 
     } 

     this.currentTimeout = setTimeout(() => { 
      this.isDelayedRunning = value; 
      this.cancelTimeout(); 
     }, this.delay); 
    } 

以上代碼是針對角度2分量的@Input。我在爲輸入創建測試用例時遇到問題,因爲我不知道如何爲這種輸入創建測試。我應該創建一個getter?我該怎麼做呢?我找不到任何參考。爲@Input函數angular 2創建測試規範

回答

1

隨着二傳手(set),你要做的就是將值賦給屬性(方法)

let fixture = TestBed.createComponent(TestComponent); 
let component = fixture.componentInstance;l 
component.isRunning = true; 
fixture.detectChanges(); 

對於超時,你可能需要做一些像

import { fakeAsync } from '@angular/core/testing; 

it('should change isDelayedRunning', fakeAsync(() => { 
    let fixture = TestBed.createComponent(TestComponent); 
    let component = fixture.componentInstance; 
    fixture.detectChanges(); 

    component.isRunning = true; 
    // wait for timeout 
    tick(200); 
    fixture.detectChanges(); 
    expect(fixture.componentInstance.isDelayedRunning).toBe(true); 
})); 

fakeAsync如果您在組件中使用templateUrl,將無法使用。所以你必須使用async。但是AFAIK沒有像tick這樣的設施,我們可以控制等待期,所以你可能不得不在測試中設定一個超時時間

import { async } from '@angular/core/testing'; 

it('should change isDelayedRunning', async(() => { 
    let fixture = TestBed.createComponent(TestComponent); 
    let component = fixture.componentInstance; 
    fixture.detectChanges(); 

    component.isRunning = true; 
    setTimeout(() => { 
    fixture.detectChanges(); 
    expect(fixture.componentInstance.isDelayedRunning).toBe(true); 
    }, 200); 
}));