0

I want to check the elements creates in html '*ngFor' with a Array in .ts , But I don't found documentation about it.

.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>

I need check in spect.ts the elements create with ngFor

3
  • I don't know how do It Commented Apr 25, 2018 at 6:27
  • Here is the documentation for the same angular.io/api/common/NgForOf Commented Apr 25, 2018 at 10:29
  • I need check in spect.ts the elements create with ngFor Commented Apr 25, 2018 at 10:44

1 Answer 1

1

try this, here i look for all elements (div.circle) and check that count isn't equal to 0 to make sure that at least one is created. .queryAll return an array but you can use .query to get only one element

 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

 }); 
Sign up to request clarification or add additional context in comments.

6 Comments

With steps: Array<number> = []; The test is correct, but this test would not be correct because steps.length == 0 and the divs would be 0.
ngFor is a structural directive , yes if length == 0 the div element will not be created
you can mock a steps array and put some elements, and check that the div is created
I know It but in .spec. with code the "Fateh Mohamed " My array,length = 0 and test is succesfull and this is a error. do you understand me ?
In my component.ts Array.length = 0 , so , in spect.ts Never count(div) > 1
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.