2017-02-20 184 views
1

功能參數在角2測試工具我這樣做:類如打字稿

fixture = TestBed.createComponent(EditableValueComponent); 

其中EditableValueComponent是一個正常的組件類。

我不知道它是如何工作的:

static createComponent<T>(component: Type<T>): ComponentFixture<T>; 

Beceause我想要做類似的事(我想簡化一些測試的東西):

export class SuperFixture<T> 
{ 
    fixture: ComponentFixture<T>; 
    component: T; 

    constructor() 
    {   
     this.fixture = TestBed.createComponent(T); // <--- problem here! 
     this.component = this.fixture.componentInstance; 
    } 
} 

的問題是:

'T'只是指一種類型,但在這裏被用作價值。'

編輯#1

我解決了這個問題是這樣的:

constructor(component) 
{ 
    this.fixture = TestBed.createComponent<T>(component); 

但我仍然不知道它是如何工作..

回答

0

您仍然需要通過實際的類(構造函數創建一個類的實例)構造函數SuperFixture。調用TestBed.createComponent調用提供的構造函數new來創建提供的類的實例。所以SuperClass簽名可能看起來像這樣:

class SuperFixture<T> 
{ 
    fixture: ComponentFixture<T>; 
    component: T; 

    // passing in the constructor for instances of T 
    constructor(componentConstructor: new() => T) 
    { 
    this.fixture = TestBed.createComponent<T>(componentConstructor); 
    this.component = this.fixture.componentInstance; 
    } 
} 
0

正在處理該答案,但不得不步行喝咖啡。 ¯_(ツ)_/

您正在使用的語言功能在TypeScript中稱爲Generic。它允許在運行時使用「類型變量」(如<T>)定義類型,它們與函數參數分開。

之前,類型變量正在通過爲函數參數,當函數預期類型T的實例,這是什麼錯誤意味着。

您所做的更改的工作原理是因爲您正在將類型變量和實例傳遞到調用中正確的位置。

SuperFixture對象獲得,當你創建它,然後將這種類型的變量傳遞給createComponent在構造函數中,與component值沿着T值。