2016-10-10 94 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

只需在使用卡组件的测试中制作一个虚拟组件。然后在测试中创建虚拟组件并检查虚拟组件的内容。它应该包含卡组件的内容 –