2016-10-10 182 views
1

我有一個組件。他的主要作用是包裝。Angular 2測試

有什麼麻煩?

方法compileComponents執行組件沒有屬性標題。這就是爲什麼,因爲我認爲,在控制檯我看到錯誤 enter image description here

問題是:如何我可以先綁定屬性,然後運行compileComponents方法?

組件模板:

<div class="card"> 
    <div *ngIf="title" class="card-header clearfix"> 
     <h3 class="card-title">{{ title }}</h3> 
    </div> 
    <div class="card-body"> 
     <ng-content></ng-content> 
    </div> 
</div> 

說明部分:

describe('CardComponent',() => { 

    let comp: CardComponent; 
    let fixture: ComponentFixture<CardComponent>; 
    let titleEl: DebugElement; // the DebugElement with the welcome message 

    // async beforeEach 
    beforeEach(async(() => { 
     TestBed.configureTestingModule({ 
      declarations: [ CardComponent ], 
     }).compileComponents(); // compile template and css 
    })); 

    // synchronous beforeEach 
    beforeEach(() => { 
     fixture = TestBed.createComponent(CardComponent); 
     comp = fixture.componentInstance; 
     titleEl = fixture.debugElement.query(By.css('.card-title')); 

     comp.title = "Greatest title"; 
     fixture.detectChanges(); // trigger initial data binding 
    }); 

    it('Card check title',() => { 
     expect(titleEl.nativeElement.textContent).toContain("Greatest title"); 
    }); 
}); 
+0

你可以給[mcve]包括你的組件和錯誤*作爲文本*? – jonrsharpe

回答

2

那是因爲你正試圖獲得元素甚至存在了。該title確定*ngIf元素是可見的。只要移動試圖讓你的元素檢測到變化後

beforeEach(() => { 
    fixture = TestBed.createComponent(CardComponent); 
    comp = fixture.componentInstance; 
    // titleEl = fixture.debugElement.query(By.css('.card-title')); 

    comp.title = 'Greatest title'; 
    fixture.detectChanges(); // trigger initial data binding 
    titleEl = fixture.debugElement.query(By.css('.card-title')); 
}); 
+0

魔法。感謝幫助。 – Tapakan

+0

也許你可以幫助如何測試? 如何綁定ng-content屬性? 我使用該組件以下列方式: 內容 在車組件我使用標籤顯示裏面的內容標籤。 – Tapakan

+0

只需在使用卡組件的測試中製作一個虛擬組件。然後在測試中創建虛擬組件並檢查虛擬組件的內容。它應該包含卡組件的內容 –