2017-09-21 38 views
1

我對單元測試相當陌生。我想知道我是否可以測試一個智能組件是否會將一些作爲@Input()傳遞給愚蠢組件(使用Angular 4+)。測試一個組件是否將一個@Input傳遞給另一個

起初,我想過檢查,如果該屬性存在:

it('should have some data', async(() => { 
    expect(component.data).toBeTruthy(); 
})); 

不過,我面臨兩個問題:1),它告訴我,如果data是真實的,但並不一定意味着它是被作爲一個傳遞輸入到我的愚蠢組件; 2)如果data屬性不存在,那麼測試套件將不會被執行。

任何提示?有沒有更好的方法來解決這個問題?謝謝。

回答

1

由於輸入綁定作爲變更檢測的一部分進行處理,因此您可以基本更改父組件上綁定所使用的屬性,然後在父組件上運行detectChanges()並檢查子組件中的輸入屬性是否已更改。沿着這些路線的東西:

parentComponent = TestBed.createComponent(BannerComponent); 
const childComponentEl = fixture.debugElement.query(By.directive(ChildComponent)); 
const childComponent = childComponentEl.injector.get(ChildComponent); 

it('should have some data', async(() => { 
    parentComponent.componentInstance.boundProperty = 3; 
    parentComponent.detectChanges(); 
    expect(childComponent.inputProperty).toBe(3); 
})); 

你可以閱讀更多關於爲什麼輸入綁定在更新:

相關問題