5. You want to test a component that shows a list of items passed as an input. Which approach correctly tests that the rendered list matches the input array?
@Component({ template: '<ul><li *ngFor="let item of items">{{item}}</li></ul>' })
class ListComponent { @Input() items: string[] = []; }
hard
A. Only check component.items property without inspecting the DOM
B. Set component.items but do not call detectChanges(), then check fixture.nativeElement.textContent
C. Call detectChanges() before setting component.items, then check component.items.length
D. Set component.items to an array, call detectChanges(), then check fixture.nativeElement.querySelectorAll('li').length
Solution
Step 1: Set input and update template
Assign the input array to component.items and call detectChanges() to update the rendered list.
Step 2: Verify rendered list length
Check the number of <li> elements in the DOM matches the input array length using querySelectorAll('li').length.
Final Answer:
Set component.items, call detectChanges(), then check li elements count -> Option D
Quick Check:
Input set + detectChanges + DOM check = correct test [OK]
Hint: Always call detectChanges() after input changes before checking DOM [OK]
Common Mistakes:
Not calling detectChanges() after input change
Checking component property only without DOM verification