I've setup a test to a simple component with ngFor. Here's the template:
<section #menuItem
*ngFor="let tab of tabs">
<h2></h2>
<div class="settings-card">
</div>
</section>
In my component, tabs is set as follows:
public get tabs() {
return this.settingsMenuDataService.menuListItems.filter(item => item.show);
}
In my spec file I mock the service:
const SettingsMenuDataServiceMock = {
menuListItems: []
}
}; ... { provide: SettingsMenuDataService, useValue: SettingsMenuDataServiceMock},
Now in my it I do like this:
it('', () => {
SettingsMenuDataServiceMock.menuListItems = [
{
show: true
},
{
show: false
},
{
show: true
}
];
fixture = TestBed.createComponent(SettingsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
const nSections = fixture.nativeElement.querySelectorAll('section').length;
expect(nSections).toEqual(SettingsMenuDataServiceMock.menuListItems.length - 1);
});
What I get in nSections is 0, because at the time of the component's creation SettingsMenuDataServiceMock.menuListItems is empty.
If I add the changes in an it before the one above, it works:
it('', () => {
SettingsMenuDataServiceMock.menuListItems = [
{
show: true
},
{
show: false
},
{
show: true
}
];
});
it('should not add a section to the DOM if its hide property is false', () => {
fixture = TestBed.createComponent(SettingsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
const nSections = fixture.nativeElement.querySelectorAll('section').length;
console.log(nSections);
expect(nSections).toEqual(SettingsMenuDataServiceMock.menuListItems.length - 1);
});
In this case the test pass. My question is: why does it work between its and how to make it work inside the relevant it.
Aucun commentaire:
Enregistrer un commentaire