首页 > 解决方案 > Angular2测试Html

问题描述

我想用 .ts 中的数组检查在 html '*ngFor' 中创建的元素,但我没有找到有关它的文档。

.ts :

steps: Array<number> = [1, 2, 3, 4, 5];

html:

<section class='mycontainer'>

  <article class="myArticle{{ steps.length }}">
    <div class='line'></div>
    <div *ngFor="let numberStep of steps;" class='circle'></div>
  </article>

</section>

我需要检查使用ngFor创建的元素的 spect.ts

标签: angularunit-testing

解决方案


试试这个,在这里我查找所有元素(div.circle)并检查 count 不等于 0 以确保至少创建了一个。.queryAll 返回一个数组,但您可以使用 .query 仅获取一个元素

 fixture = TestBed.createComponent(yourComponent);
 comp = fixture.componentInstance;

it('ngFor div should be created', () =>  {
      fixture.detectChanges();
      let ngForElement: DebugElement;
      ngForElement= fixture.debugElement.queryAll(By.css('div.circle'));
      expect((ngForElement.length).not.toBe(0); // check that ngFor contain at least one element

 }); 

推荐阅读