2017-03-07 67 views
3

說我有一個角2組件有兩個輸入參數:測試角2組件與構造函數的參數

@Component{... (omitted for clarity)} 
export class SomeComponent { 

@Input() a: number 
@Input() b: number 

} 

當我想測試這個組件我有類似:

beforeEach(async(() => { 
    TestBed.configureTestingModule({ 
     declarations: [ 
     SomeComponent, 
     ], 
    }) 
    .compileComponents(); 
    })); 

    beforeEach(() => { 
    fixture = TestBed.createComponent(SomeComponent); 
    component = fixture.componentInstance; 
    fixture.detectChanges(); 
    }); 

createComponent調用不會接受任何參數,也不允許我調用構造函數。我如何實例化/測試組件的各種數值?

+2

'成分。 a = 1; component.b = 2;'? –

+0

這會在實例化後改變值。這會導致html的模板使用當時爲(默認)0的構造函數值。 –

+1

這是設置這些值的唯一方法。沒有首先構造對象就無法更改對象的字段。你可以在調用fixture.detectChanges()之前做到這一點。 –

回答

0

尖的由JB Nizet甌,當組件已經@input參數,則需要初始化他們在beforeEach(): ```

beforeEach(() => { 
    fixture = TestBed.createComponent(SomeComponent); 
    component = fixture.componentInstance; 
    component.a = 1; 
    component.b = 2; 
    fixture.detectChanges(); 
}); 

```