2017-02-14 24 views
0

我想通過DebugElements循環來確保元素描述的對象具有某些屬性。例如,我可能希望確保顯示屏僅顯示那些今天有預約的患者,而不顯示可用患者的完整列表。如何從Angular2 DebugElement訪問範圍數據?

如何從調試元素訪問範圍數據?

例如:

:在下面的代碼,所述page可變包頻繁調試元件的搜索到一個單一的類。在這種情況下,它爲同一個列表組件的兩個實現提供調試元素,並且每個列表組件根據與此問題無關的標準顯示不同的患者列表。

it("lists zero patients from other staff members that the staff member who is logged in",()=>{ 
    var element : DebugElement, list : any; 
    var user : string = component.credentials.username; 
    var notMyPatientCount : number = 0; 
    for (list of [page.primaryPatients, page.patientBacklog]){ 
     for(element of list){ 
      var patient = /* I need something to put here to extract the PatientSummary object that is displayed in this element */; 
     } 
    } 
    expect(notMyPatientCount).toBe(0, "When filtered, the display only holds patients assigned to the current user."); 
}); 
+0

這只是一個觀察不是一個答案,但似乎這個邏輯在服務和爲測試屬於它屬於該服務的測試套件。我真的很困惑,因爲我看到很多像這樣的測試,我不明白他們的目的。我意識到組件正在過濾數據,但也許該過濾器應該在服務中...我真的不知道 –

+0

我的原始實現使用管道服務來完成這項工作,但管道導致無效區域引用的錯誤或某事像那樣。我試圖解決這個問題幾天,然後發現一個像上面的實現,並意識到我可以繞過導致我這麼多麻煩的管道。 –

+1

我明白這是有道理的。 Pipe並不是一項真正的服務,它更多的是放入所有視圖命名空間的功能。我在想更多,你會想要注入一個常規的服務,並使用它,因爲服務比組件更容易測試。感謝您的解釋。 –

回答

1

測試頁面包含DebugElement(click here for DebugElement API)的API參考。

我以前曾經閱讀過這個文檔,但是我錯過了名爲「componentInstance」的屬性指的是附加到調試元素而不是測試範圍的組件實例。

要訪問PatientSummary對象在DebugElement被使用,我用下面的代碼:

/** 
* 
* @Component(...) 
* export class PatientListItemComponent { 
*   ... 
*   patientSummary : PatientSummary; 
*   ... 
* } 
* 
*/ 

var component : PatientListItemComponent = element.componentInstance; 
var patient : PatientSummary = component.patientSummary;