Я настроил тест для простого компонента с помощью ngFor.
Вот шаблон:
<section #menuItem
*ngFor="let tab of tabs">
<h2>{{tab.name}}</h2>
<div class="settings-card">
{{tab.content}}
</div>
</section>
В моем компоненте вкладки настроены следующим образом:
public get tabs() {
return this.settingsMenuDataService.menuListItems.filter(item => item.show);
}
В моем spec-файле я издеваюсь над сервисом:
const SettingsMenuDataServiceMock = {
menuListItems: []
}
};
{ provide: SettingsMenuDataService, useValue: SettingsMenuDataServiceMock},
Теперь в моем it
мне так:
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);
});
То, что я получаю в nSections
, равно 0, потому что во время создания компонента SettingsMenuDataServiceMock.menuListItems
пусто.
Если я добавлю изменения в it
перед приведенным выше, это сработает:
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);
});
В этом случае тест пройден.
Мой вопрос: почему он работает между it
с и как заставить его работать внутри соответствующих it
.