Reputation: 171
I am trying to write unit test cases for view children query list, where I am looping to each element ref & taking width of item to check weather it will fit within div or not. So please tell me how to create a mock DOM for Querylist reference. Below is the code, span with reference #listEle is flex items
Test.component.html:
<div #containerRef>
<span *ngFor="let val of data| slice: 0:linksShown;" #listEle>
<a href="val.link">{{ val.name }}</a>
</span>
</div>
Test.component.ts:
import { ElementRef, OnInit, QueryList, ViewChild, ViewChildren } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.scss'],
})
export class TestComponent implements OnInit {
@Input() data;
@ViewChild('containerRef', { read: ElementRef, static: true }) containerRef:
ElementRef;
listRef: QueryList<ElementRef>;
@ViewChildren('listEle') set listEle(ref: QueryList<ElementRef>) {
this.listRef = ref;
}
linksShown: number;
constructor() {}
ngOnInit() {
let items = 0;
let count = 0;
this.listRef.toArray().forEach((ele) => {
count += ele.nativeElement.clientWidth;
if (count < this.containerRef.nativeElement.clientWidth) {
count++;
}
});
this.linksShown = count;
}
}
Test.component.spec.ts:
import { Component, ElementRef, ViewChild, ViewChildren } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, tick } from
'@angular/core/testing';
import { TestComponent } from './host-links.component';
describe('TestComponent', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
const data = [
{ name: 'test1', link: '/test1' },
{ parentName: 'test2', link: '/test2' }
]
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [TestComponent],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
component.data = data;
fixture.detectChanges();
});
it('should get the linkShown count', () => {
component.OnInit();
expect(component.linksShown).toEqual(2);
});
})
Upvotes: 2
Views: 298