Fixing unit test after last rebase + lint

This commit is contained in:
Vito Albano
2024-04-10 01:52:07 +01:00
committed by VitoAlbano
parent bb977c9194
commit c56aff3aea
3 changed files with 317 additions and 339 deletions

View File

@@ -39,8 +39,15 @@ import {
} from '../../../mock'; } from '../../../mock';
import { SearchFacetFiltersService } from '../../services/search-facet-filters.service'; import { SearchFacetFiltersService } from '../../services/search-facet-filters.service';
import { SearchFacetFieldComponent } from '../search-facet-field/search-facet-field.component'; import { SearchFacetFieldComponent } from '../search-facet-field/search-facet-field.component';
import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatExpansionPanelHarness } from '@angular/material/expansion/testing';
import { MatCheckboxHarness } from '@angular/material/checkbox/testing';
import { MatButtonHarness } from '@angular/material/button/testing';
import { MatInputHarness } from '@angular/material/input/testing';
describe('SearchFilterComponent', () => { describe('SearchFilterComponent', () => {
let loader: HarnessLoader;
let fixture: ComponentFixture<SearchFilterComponent>; let fixture: ComponentFixture<SearchFilterComponent>;
let component: SearchFilterComponent; let component: SearchFilterComponent;
let queryBuilder: SearchQueryBuilderService; let queryBuilder: SearchQueryBuilderService;
@@ -60,8 +67,9 @@ describe('SearchFilterComponent', () => {
fixture = TestBed.createComponent(SearchFilterComponent); fixture = TestBed.createComponent(SearchFilterComponent);
appConfigService = TestBed.inject(AppConfigService); appConfigService = TestBed.inject(AppConfigService);
const translationService = fixture.debugElement.injector.get(TranslationService); const translationService = fixture.debugElement.injector.get(TranslationService);
spyOn(translationService, 'instant').and.callFake((key) => key ? `${key}_translated` : null); spyOn(translationService, 'instant').and.callFake((key) => (key ? `${key}_translated` : null));
component = fixture.componentInstance; component = fixture.componentInstance;
loader = TestbedHarnessEnvironment.loader(fixture);
}); });
afterEach(() => fixture.destroy()); afterEach(() => fixture.destroy());
@@ -73,27 +81,41 @@ describe('SearchFilterComponent', () => {
spyOn(queryBuilder, 'execute').and.stub(); spyOn(queryBuilder, 'execute').and.stub();
queryBuilder.config = { queryBuilder.config = {
categories: [], categories: [],
facetFields: { fields: [ facetFields: {
fields: [
{ label: 'f1', field: 'f1' }, { label: 'f1', field: 'f1' },
{ label: 'f2', field: 'f2' } { label: 'f2', field: 'f2' }
]}, ]
},
facetQueries: { facetQueries: {
queries: [] queries: []
} }
}; };
searchFacetFiltersService.responseFacets = [ searchFacetFiltersService.responseFacets = [
{ type: 'field', label: 'f1', field: 'f1', buckets: new SearchFilterList([ {
type: 'field',
label: 'f1',
field: 'f1',
buckets: new SearchFilterList([
{ label: 'b1', count: 10, filterQuery: 'filter', checked: true }, { label: 'b1', count: 10, filterQuery: 'filter', checked: true },
{ label: 'b2', count: 1, filterQuery: 'filter2' }]) }, { label: 'b2', count: 1, filterQuery: 'filter2' }
])
},
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList([]) } { type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList([]) }
]; ];
queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]); queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]);
const serverResponseFields: any = [ const serverResponseFields: any = [
{ type: 'field', label: 'f1', field: 'f1', buckets: [ {
type: 'field',
label: 'f1',
field: 'f1',
buckets: [
{ label: 'b1', metrics: [{ value: { count: 6 } }], filterQuery: 'filter' }, { label: 'b1', metrics: [{ value: { count: 6 } }], filterQuery: 'filter' },
{ label: 'b2', metrics: [{value: {count: 1}}], filterQuery: 'filter2' }] }, { label: 'b2', metrics: [{ value: { count: 1 } }], filterQuery: 'filter2' }
]
},
{ type: 'field', label: 'f2', field: 'f2', buckets: [] } { type: 'field', label: 'f2', field: 'f2', buckets: [] }
]; ];
const data = { const data = {
@@ -117,27 +139,41 @@ describe('SearchFilterComponent', () => {
spyOn(queryBuilder, 'execute').and.stub(); spyOn(queryBuilder, 'execute').and.stub();
queryBuilder.config = { queryBuilder.config = {
categories: [], categories: [],
facetFields: { fields: [ facetFields: {
fields: [
{ label: 'f1', field: 'f1' }, { label: 'f1', field: 'f1' },
{ label: 'f2', field: 'f2' } { label: 'f2', field: 'f2' }
]}, ]
},
facetQueries: { facetQueries: {
queries: [] queries: []
} }
}; };
searchFacetFiltersService.responseFacets = [ searchFacetFiltersService.responseFacets = [
{ type: 'field', label: 'f1', field: 'f1', buckets: new SearchFilterList([ {
type: 'field',
label: 'f1',
field: 'f1',
buckets: new SearchFilterList([
{ label: 'b1', count: 10, filterQuery: 'filter', checked: true }, { label: 'b1', count: 10, filterQuery: 'filter', checked: true },
{ label: 'b2', count: 1, filterQuery: 'filter2' }]) }, { label: 'b2', count: 1, filterQuery: 'filter2' }
])
},
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList([]) } { type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList([]) }
]; ];
queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]); queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]);
const serverResponseFields: any = [ const serverResponseFields: any = [
{ type: 'field', label: 'f1', field: 'f1', buckets: [ {
type: 'field',
label: 'f1',
field: 'f1',
buckets: [
{ label: 'b1', metrics: [{ value: { count: 6 } }], filterQuery: 'filter' }, { label: 'b1', metrics: [{ value: { count: 6 } }], filterQuery: 'filter' },
{ label: 'b2', metrics: [{value: {count: 1}}], filterQuery: 'filter2' }] }, { label: 'b2', metrics: [{ value: { count: 1 } }], filterQuery: 'filter2' }
]
},
{ type: 'field', label: 'f2', field: 'f2', buckets: [] } { type: 'field', label: 'f2', field: 'f2', buckets: [] }
]; ];
const data = { const data = {
@@ -161,19 +197,27 @@ describe('SearchFilterComponent', () => {
spyOn(queryBuilder, 'execute').and.stub(); spyOn(queryBuilder, 'execute').and.stub();
queryBuilder.config = { queryBuilder.config = {
categories: [], categories: [],
facetFields: { fields: [ facetFields: {
fields: [
{ label: 'f1', field: 'f1' }, { label: 'f1', field: 'f1' },
{ label: 'f2', field: 'f2' } { label: 'f2', field: 'f2' }
]}, ]
},
facetQueries: { facetQueries: {
queries: [] queries: []
} }
}; };
searchFacetFiltersService.responseFacets = [ searchFacetFiltersService.responseFacets = [
{ type: 'field', label: 'f1', field: 'f1', buckets: new SearchFilterList([ {
type: 'field',
label: 'f1',
field: 'f1',
buckets: new SearchFilterList([
{ label: 'b1', count: 10, filterQuery: 'filter', checked: true }, { label: 'b1', count: 10, filterQuery: 'filter', checked: true },
{ label: 'b2', count: 1, filterQuery: 'filter2' }]) }, { label: 'b2', count: 1, filterQuery: 'filter2' }
])
},
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList() } { type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList() }
]; ];
queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]); queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]);
@@ -201,7 +245,8 @@ describe('SearchFilterComponent', () => {
buckets: new SearchFilterList([ buckets: new SearchFilterList([
{ label: 'q1', query: 'q1', checked: true, metrics: [{ value: { count: 1 } }] }, { label: 'q1', query: 'q1', checked: true, metrics: [{ value: { count: 1 } }] },
{ label: 'q2', query: 'q2', checked: false, metrics: [{ value: { count: 1 } }] }, { label: 'q2', query: 'q2', checked: false, metrics: [{ value: { count: 1 } }] },
{ label: 'q3', query: 'q3', checked: true, metrics: [{value: {count: 1}}] }]) { label: 'q3', query: 'q3', checked: true, metrics: [{ value: { count: 1 } }] }
])
} as any; } as any;
searchFacetFiltersService.responseFacets = [queryResponse]; searchFacetFiltersService.responseFacets = [queryResponse];
@@ -219,7 +264,6 @@ describe('SearchFilterComponent', () => {
}); });
describe('widgets', () => { describe('widgets', () => {
it('should have expandable categories', async () => { it('should have expandable categories', async () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
@@ -229,24 +273,8 @@ describe('SearchFilterComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel')); const panels = await loader.getAllHarnesses(MatExpansionPanelHarness);
expect(panels.length).toBe(1); expect(panels.length).toBe(1);
const element: HTMLElement = panels[0].nativeElement;
(element.childNodes[0] as HTMLElement).click();
fixture.detectChanges();
await fixture.whenStable();
expect(element.classList.contains('mat-expanded')).toBeTruthy();
(element.childNodes[0] as HTMLElement).click();
fixture.detectChanges();
await fixture.whenStable();
expect(element.classList.contains('mat-expanded')).toEqual(false);
}); });
it('should not show the disabled widget', async () => { it('should not show the disabled widget', async () => {
@@ -256,7 +284,7 @@ describe('SearchFilterComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel')); const panels = await loader.getAllHarnesses(MatExpansionPanelHarness);
expect(panels.length).toBe(0); expect(panels.length).toBe(0);
}); });
@@ -267,21 +295,11 @@ describe('SearchFilterComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel')); const panels = await loader.getAllHarnesses(MatExpansionPanelHarness);
expect(panels.length).toBe(1); expect(panels.length).toBe(1);
const title = fixture.debugElement.query(By.css('.mat-expansion-panel-header-title')); expect(await panels[0].getTitle()).toBe('Type');
expect(title.nativeElement.innerText.trim()).toBe('Type'); expect(await panels[0].isExpanded()).toBe(true);
const element: HTMLElement = panels[0].nativeElement;
expect(element.classList.contains('mat-expanded')).toBeTruthy();
(element.childNodes[0] as HTMLElement).click();
fixture.detectChanges();
await fixture.whenStable();
expect(element.classList.contains('mat-expanded')).toEqual(false);
}); });
it('should show the widgets only if configured', async () => { it('should show the widgets only if configured', async () => {
@@ -291,11 +309,11 @@ describe('SearchFilterComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel')); const panels = await loader.getAllHarnesses(MatExpansionPanelHarness);
expect(panels.length).toBe(2); expect(panels.length).toBe(2);
const titleElements = fixture.debugElement.queryAll(By.css('.mat-expansion-panel-header-title')); expect(await panels[0].getTitle()).toBe('Name');
expect(titleElements.map(title => title.nativeElement.innerText.trim())).toEqual(['Name', 'Type']); expect(await panels[1].getTitle()).toBe('Type');
}); });
it('should be update the search query when name changed', async () => { it('should be update the search query when name changed', async () => {
@@ -305,17 +323,19 @@ describe('SearchFilterComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
let panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel'));
let panels = await loader.getAllHarnesses(MatExpansionPanelHarness);
expect(panels.length).toBe(6); expect(panels.length).toBe(6);
const inputElement = fixture.debugElement.query(By.css('[data-automation-id="expansion-panel-Name"] input')); const inputElement = fixture.debugElement.query(By.css('[data-automation-id="expansion-panel-Name"] input'));
inputElement.triggerEventHandler('change', { target: { value: '*' } }); inputElement.triggerEventHandler('change', { target: { value: '*' } });
expect(queryBuilder.update).toHaveBeenCalled(); expect(queryBuilder.update).toHaveBeenCalled();
queryBuilder.executed.next(mockSearchResult); queryBuilder.executed.next(mockSearchResult);
fixture.detectChanges(); fixture.detectChanges();
panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel')); panels = await loader.getAllHarnesses(MatExpansionPanelHarness);
expect(panels.length).toBe(8); expect(panels.length).toBe(8);
}); });
@@ -326,19 +346,20 @@ describe('SearchFilterComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const inputElement = fixture.debugElement.query(By.css('[data-automation-id="expansion-panel-Name"] input')); const input = await loader.getHarness(MatInputHarness);
inputElement.triggerEventHandler('change', { target: { value: '*' } }); await input.setValue('*');
queryBuilder.executed.next(getMockSearchResultWithResponseBucket()); queryBuilder.executed.next(getMockSearchResultWithResponseBucket());
fixture.detectChanges(); fixture.detectChanges();
const panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel')); const panels = await loader.getAllHarnesses(MatExpansionPanelHarness);
expect(panels.length).toBe(9); expect(panels.length).toBe(9);
}); });
it('should show the long facet options list with pagination', () => { it('should show the long facet options list with pagination', async () => {
const panel = '[data-automation-id="expansion-panel-Size facet queries"]'; const showMoreButton = MatButtonHarness.with({ selector: `[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]` });
const showLessButton = MatButtonHarness.with({ selector: `[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]` });
appConfigService.config.search = searchFilter; appConfigService.config.search = searchFilter;
queryBuilder.resetToDefaults(); queryBuilder.resetToDefaults();
@@ -346,58 +367,51 @@ describe('SearchFilterComponent', () => {
queryBuilder.executed.next(mockSearchResult); queryBuilder.executed.next(mockSearchResult);
fixture.detectChanges(); fixture.detectChanges();
let sizes = getAllMenus(`${panel} mat-checkbox`, fixture); const panel = await loader.getHarness(
expect(sizes).toEqual(stepOne); MatExpansionPanelHarness.with({
selector: `[data-automation-id="expansion-panel-Size facet queries"]`
})
);
let moreButton = fixture.debugElement.query(By.css(`${panel} button[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]`)); let sizes = await panel.getAllHarnesses(MatCheckboxHarness);
let lessButton = fixture.debugElement.query(By.css(`${panel} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`)); let sizeLabels = await Promise.all(sizes.map((element) => element.getLabelText()));
expect(sizeLabels).toEqual(stepOne);
expect(lessButton).toEqual(null); let moreButton = await loader.getHarness(showMoreButton);
expect(moreButton).toBeDefined(); expect(await loader.hasHarness(showLessButton)).toBe(false);
moreButton.triggerEventHandler('click', {}); await moreButton.click();
fixture.detectChanges();
sizes = getAllMenus(`${panel} mat-checkbox`, fixture); sizes = await panel.getAllHarnesses(MatCheckboxHarness);
expect(sizes).toEqual(stepTwo); sizeLabels = await Promise.all(sizes.map((element) => element.getLabelText()));
expect(sizeLabels).toEqual(stepTwo);
moreButton = fixture.debugElement.query(By.css(`${panel} button[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]`)); moreButton = await loader.getHarness(showMoreButton);
lessButton = fixture.debugElement.query(By.css(`${panel} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`)); expect(await loader.hasHarness(showLessButton)).toBe(true);
expect(lessButton).toBeDefined(); await moreButton.click();
expect(moreButton).toBeDefined();
moreButton.triggerEventHandler('click', {}); sizes = await panel.getAllHarnesses(MatCheckboxHarness);
fixture.detectChanges(); sizeLabels = await Promise.all(sizes.map((element) => element.getLabelText()));
sizes = getAllMenus(`${panel} mat-checkbox`, fixture); expect(sizeLabels).toEqual(stepThree);
expect(sizes).toEqual(stepThree); expect(await loader.hasHarness(showMoreButton)).toBe(false);
let lessButton = await loader.getHarness(showLessButton);
await lessButton.click();
moreButton = fixture.debugElement.query(By.css(`${panel} button[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]`)); sizes = await panel.getAllHarnesses(MatCheckboxHarness);
lessButton = fixture.debugElement.query(By.css(`${panel} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`)); sizeLabels = await Promise.all(sizes.map((element) => element.getLabelText()));
expect(lessButton).toBeDefined(); expect(sizeLabels).toEqual(stepTwo);
expect(moreButton).toEqual(null);
lessButton.triggerEventHandler('click', {}); expect(await loader.hasHarness(showMoreButton)).toBe(true);
fixture.detectChanges(); lessButton = await loader.getHarness(showLessButton);
await lessButton.click();
sizes = getAllMenus(`${panel} mat-checkbox`, fixture); sizes = await panel.getAllHarnesses(MatCheckboxHarness);
expect(sizes).toEqual(stepTwo); sizeLabels = await Promise.all(sizes.map((element) => element.getLabelText()));
expect(sizeLabels).toEqual(stepOne);
moreButton = fixture.debugElement.query(By.css(`${panel} button[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]`)); expect(await loader.hasHarness(showMoreButton)).toBe(true);
lessButton = fixture.debugElement.query(By.css(`${panel} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`)); expect(await loader.hasHarness(showLessButton)).toBe(false);
expect(lessButton).toBeDefined();
expect(moreButton).toBeDefined();
lessButton.triggerEventHandler('click', {});
fixture.detectChanges();
sizes = getAllMenus(`${panel} mat-checkbox`, fixture);
expect(sizes).toEqual(stepOne);
moreButton = fixture.debugElement.query(By.css(`${panel} button[title="SEARCH.FILTER.ACTIONS.SHOW-MORE"]`));
lessButton = fixture.debugElement.query(By.css(`${panel} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`));
expect(lessButton).toEqual(null);
expect(moreButton).toBeDefined();
}); });
it('should not show facets if filter is not available', () => { it('should not show facets if filter is not available', () => {
@@ -416,8 +430,8 @@ describe('SearchFilterComponent', () => {
expect(facetElement).toEqual(null); expect(facetElement).toEqual(null);
}); });
it('should search the facets options and select it', () => { it('should search the facets options and select it', async () => {
const panel = '[data-automation-id="expansion-panel-Size facet queries"]'; const panelSelector = '[data-automation-id="expansion-panel-Size facet queries"]';
appConfigService.config.search = searchFilter; appConfigService.config.search = searchFilter;
queryBuilder.resetToDefaults(); queryBuilder.resetToDefaults();
fixture.detectChanges(); fixture.detectChanges();
@@ -426,41 +440,39 @@ describe('SearchFilterComponent', () => {
spyOn(queryBuilder, 'update').and.stub(); spyOn(queryBuilder, 'update').and.stub();
const inputElement = fixture.debugElement.query(By.css(`${panel} input`)); const panel = await loader.getHarness(
inputElement.nativeElement.value = 'Extra'; MatExpansionPanelHarness.with({
inputElement.nativeElement.dispatchEvent(new Event('input')); selector: panelSelector
fixture.detectChanges(); })
);
let filteredMenu = getAllMenus(`${panel} mat-checkbox`, fixture); const input = await panel.getHarness(MatInputHarness);
expect(filteredMenu).toEqual(['Extra Small (10239)']); await input.setValue('Extra');
inputElement.nativeElement.value = 'my'; let checkboxes = await panel.getAllHarnesses(MatCheckboxHarness);
inputElement.nativeElement.dispatchEvent(new Event('input')); expect(checkboxes.length).toBe(1);
fixture.detectChanges(); expect(await checkboxes[0].getLabelText()).toBe('Extra Small (10239)');
filteredMenu = getAllMenus(`${panel} mat-checkbox`, fixture); await input.setValue('my');
expect(filteredMenu).toEqual(filteredResult);
const clearButton = fixture.debugElement.query(By.css(`${panel} mat-form-field button`)); checkboxes = await panel.getAllHarnesses(MatCheckboxHarness);
clearButton.triggerEventHandler('click', {}); let labels = await Promise.all(checkboxes.map((element) => element.getLabelText()));
fixture.detectChanges(); expect(labels).toEqual(filteredResult);
filteredMenu = getAllMenus(`${panel} mat-checkbox`, fixture); const clearButton = await panel.getHarness(MatButtonHarness.with({ selector: '[title="SEARCH.FILTER.BUTTONS.CLEAR"]' }));
expect(filteredMenu).toEqual(stepOne); await clearButton.click();
const firstOption = fixture.debugElement.query(By.css(`${panel} mat-checkbox`)); checkboxes = await panel.getAllHarnesses(MatCheckboxHarness);
firstOption.triggerEventHandler('change', { checked: true }); labels = await Promise.all(checkboxes.map((element) => element.getLabelText()));
fixture.detectChanges(); expect(labels).toEqual(stepOne);
const checkedOption = fixture.debugElement.query(By.css(`${panel} mat-checkbox.mat-mdc-checkbox-checked`));
expect(checkedOption.nativeElement.innerText).toEqual('Extra Small (10239)');
await checkboxes[0].check();
expect(queryBuilder.update).toHaveBeenCalledTimes(1); expect(queryBuilder.update).toHaveBeenCalledTimes(1);
}); });
it('should preserve the filter state if other fields edited', () => { it('should preserve the filter state if other fields edited', async () => {
const panel1 = '[data-automation-id="expansion-panel-Size facet queries"]'; const panel1Selector = '[data-automation-id="expansion-panel-Size facet queries"]';
const panel2 = '[data-automation-id="expansion-panel-Type facet queries"]'; const panel2selector = '[data-automation-id="expansion-panel-Type facet queries"]';
appConfigService.config.search = searchFilter; appConfigService.config.search = searchFilter;
queryBuilder.resetToDefaults(); queryBuilder.resetToDefaults();
fixture.detectChanges(); fixture.detectChanges();
@@ -468,33 +480,33 @@ describe('SearchFilterComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
spyOn(queryBuilder, 'update').and.stub(); spyOn(queryBuilder, 'update').and.stub();
const inputElement = fixture.debugElement.query(By.css(`${panel1} input`)); const inputElement = fixture.debugElement.query(By.css(`${panel1Selector} input`));
inputElement.nativeElement.value = 'my'; inputElement.nativeElement.value = 'my';
inputElement.nativeElement.dispatchEvent(new Event('input')); inputElement.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges(); fixture.detectChanges();
let filteredMenu = getAllMenus(`${panel1} mat-checkbox`, fixture); const panel1 = await loader.getHarness(MatExpansionPanelHarness.with({ selector: panel1Selector }));
expect(filteredMenu).toEqual(filteredResult);
const firstOption = fixture.debugElement.query(By.css(`${panel1} mat-checkbox`)); let checkboxes = await panel1.getAllHarnesses(MatCheckboxHarness);
firstOption.triggerEventHandler('change', { checked: true }); let labels = await Promise.all(checkboxes.map((element) => element.getLabelText()));
fixture.detectChanges(); expect(labels).toEqual(filteredResult);
let panel1CheckedOption = fixture.debugElement.query(By.css(`${panel1} mat-checkbox.mat-mdc-checkbox-checked`)); await checkboxes[0].check();
expect(panel1CheckedOption.nativeElement.innerText).toEqual('my1 (806)'); expect(await checkboxes[0].isChecked()).toBe(true);
expect(await checkboxes[0].getLabelText()).toBe('my1 (806)');
const panel2Options = fixture.debugElement.query(By.css(`${panel2} mat-checkbox`)); const panel2 = await loader.getHarness(MatExpansionPanelHarness.with({ selector: panel2selector }));
panel2Options.triggerEventHandler('change', { checked: true }); checkboxes = await panel2.getAllHarnesses(MatCheckboxHarness);
fixture.detectChanges(); await checkboxes[0].check();
expect(await checkboxes[0].isChecked()).toBe(true);
expect(await checkboxes[0].getLabelText()).toBe('SEARCH.FACET_QUERIES.MIMETYPE (13)');
const panel2CheckedOption = fixture.debugElement.query(By.css(`${panel2} mat-checkbox.mat-mdc-checkbox-checked`)); checkboxes = await panel1.getAllHarnesses(MatCheckboxHarness);
expect(panel2CheckedOption.nativeElement.innerText).toEqual('SEARCH.FACET_QUERIES.MIMETYPE (13)'); labels = await Promise.all(checkboxes.map((element) => element.getLabelText()));
expect(labels).toEqual(filteredResult);
filteredMenu = getAllMenus(`${panel1} mat-checkbox`, fixture); const checkedOption = await panel1.getHarness(MatCheckboxHarness.with({ checked: true }));
expect(filteredMenu).toEqual(filteredResult); expect(await checkedOption.getLabelText()).toBe('my1 (806)');
panel1CheckedOption = fixture.debugElement.query(By.css(`${panel1} mat-checkbox.mat-mdc-checkbox-checked`));
expect(panel1CheckedOption.nativeElement.innerText).toEqual('my1 (806)');
expect(queryBuilder.update).toHaveBeenCalledTimes(2); expect(queryBuilder.update).toHaveBeenCalledTimes(2);
}); });
@@ -513,11 +525,10 @@ describe('SearchFilterComponent', () => {
expect(component.queryBuilder.queryFragments).toEqual({}); expect(component.queryBuilder.queryFragments).toEqual({});
expect(queryBuilder.resetToDefaults).toHaveBeenCalled(); expect(queryBuilder.resetToDefaults).toHaveBeenCalled();
}); });
}); });
}); });
export const getAllMenus = (regex, fixture: ComponentFixture<any>): string[] => { export const getAllMenus = (regex, fixture: ComponentFixture<any>): string[] => {
const elements = fixture.debugElement.queryAll(By.css(regex)); const elements = fixture.debugElement.queryAll(By.css(regex));
return Array.from(elements).map(element => element.nativeElement.innerText); return Array.from(elements).map((element) => element.nativeElement.innerText);
}; };

View File

@@ -18,31 +18,26 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser'; import { By } from '@angular/platform-browser';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { ProcessServiceCloudTestingModule } from './../../testing/process-service-cloud.testing.module';
import { GroupCloudModule } from '../group-cloud.module'; import { GroupCloudModule } from '../group-cloud.module';
import { GroupCloudComponent } from './group-cloud.component'; import { GroupCloudComponent } from './group-cloud.component';
import { CoreTestingModule } from '@alfresco/adf-core';
import { DebugElement, SimpleChange } from '@angular/core'; import { DebugElement, SimpleChange } from '@angular/core';
import { IdentityGroupService } from '../services/identity-group.service'; import { IdentityGroupService } from '../services/identity-group.service';
import { mockFoodGroups, mockMeatChicken, mockVegetableAubergine } from '../mock/group-cloud.mock'; import { mockFoodGroups, mockMeatChicken, mockVegetableAubergine } from '../mock/group-cloud.mock';
import { TranslationMock, TranslationService } from '@alfresco/adf-core'; import { HarnessLoader } from '@angular/cdk/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatChipHarness, MatChipListHarness } from '@angular/material/chips/testing';
import { MatIconHarness } from '@angular/material/icon/testing';
import { MatInputHarness } from '@angular/material/input/testing';
describe('GroupCloudComponent', () => { describe('GroupCloudComponent', () => {
let loader: HarnessLoader;
let component: GroupCloudComponent; let component: GroupCloudComponent;
let fixture: ComponentFixture<GroupCloudComponent>; let fixture: ComponentFixture<GroupCloudComponent>;
let element: HTMLElement; let element: HTMLElement;
let identityGroupService: IdentityGroupService; let identityGroupService: IdentityGroupService;
let findGroupsByNameSpy; let findGroupsByNameSpy: jasmine.Spy;
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions
/**
* get the native element for the selector
*
* @param selector selector
* @returns native element
*/
function getElement<T = HTMLElement>(selector: string): T {
return fixture.nativeElement.querySelector(selector);
}
/** /**
* search group by value * search group by value
@@ -50,14 +45,9 @@ describe('GroupCloudComponent', () => {
* @param value element input value * @param value element input value
*/ */
async function searchGroup(value: string) { async function searchGroup(value: string) {
const input = getElement<HTMLInputElement>('input'); const input = await loader.getHarness(MatInputHarness);
input.focus(); await input.focus();
input.value = value; await input.setValue(value);
input.dispatchEvent(new Event('keyup'));
input.dispatchEvent(new Event('input'));
await fixture.whenStable();
fixture.detectChanges();
} }
/** /**
@@ -66,17 +56,10 @@ describe('GroupCloudComponent', () => {
* @param value value * @param value value
*/ */
async function searchGroupsAndBlur(value: string) { async function searchGroupsAndBlur(value: string) {
const input = getElement<HTMLInputElement>('input'); const input = await loader.getHarness(MatInputHarness);
input.focus(); await input.focus();
input.value = value; await input.setValue(value);
input.dispatchEvent(new Event('keyup')); await input.blur();
input.dispatchEvent(new Event('input'));
await fixture.whenStable();
fixture.detectChanges();
input.blur();
fixture.detectChanges();
} }
/** /**
@@ -90,20 +73,14 @@ describe('GroupCloudComponent', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [ imports: [TranslateModule.forRoot(), CoreTestingModule, ProcessServiceCloudTestingModule, GroupCloudModule]
TranslateModule.forRoot(),
NoopAnimationsModule,
GroupCloudModule
],
providers: [
{ provide: TranslationService, useClass: TranslationMock }
]
}); });
fixture = TestBed.createComponent(GroupCloudComponent); fixture = TestBed.createComponent(GroupCloudComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
element = fixture.nativeElement; element = fixture.nativeElement;
identityGroupService = TestBed.inject(IdentityGroupService); identityGroupService = TestBed.inject(IdentityGroupService);
loader = TestbedHarnessEnvironment.loader(fixture);
}); });
it('should populate placeholder when title is present', () => { it('should populate placeholder when title is present', () => {
@@ -116,7 +93,6 @@ describe('GroupCloudComponent', () => {
}); });
describe('Search group', () => { describe('Search group', () => {
beforeEach(() => { beforeEach(() => {
fixture.detectChanges(); fixture.detectChanges();
findGroupsByNameSpy = spyOn(identityGroupService, 'search').and.returnValue(of(mockFoodGroups)); findGroupsByNameSpy = spyOn(identityGroupService, 'search').and.returnValue(of(mockFoodGroups));
@@ -209,19 +185,19 @@ describe('GroupCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
}); });
it('should not pre-select any group when preSelectGroups is empty - single mode', () => { it('should not pre-select any group when preSelectGroups is empty - single mode', async () => {
component.mode = 'single'; component.mode = 'single';
fixture.detectChanges(); fixture.detectChanges();
const chips = fixture.debugElement.queryAll(By.css('mat-chip')); const chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toEqual(0); expect(chips.length).toEqual(0);
}); });
it('should not pre-select any group when preSelectGroups is empty - multiple mode', () => { it('should not pre-select any group when preSelectGroups is empty - multiple mode', async () => {
component.mode = 'multiple'; component.mode = 'multiple';
fixture.detectChanges(); fixture.detectChanges();
const chips = fixture.debugElement.queryAll(By.css('mat-chip')); const chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toEqual(0); expect(chips.length).toEqual(0);
}); });
}); });
@@ -236,10 +212,11 @@ describe('GroupCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
}); });
it('should show only one mat chip with the first preSelectedGroup', () => { it('should show only one mat chip with the first preSelectedGroup', async () => {
const chips = fixture.debugElement.queryAll(By.css('mat-chip-row')); const chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toEqual(1); expect(chips.length).toEqual(1);
expect(chips[0].attributes['data-automation-id']).toEqual(`adf-cloud-group-chip-${mockVegetableAubergine.name}`); const testId = await (await chips[0].host()).getAttribute('data-automation-id');
expect(testId).toEqual(`adf-cloud-group-chip-${mockVegetableAubergine.name}`);
}); });
}); });
@@ -253,12 +230,13 @@ describe('GroupCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
}); });
it('should render all preselected groups', () => { it('should render all preselected groups', async () => {
component.mode = 'multiple'; component.mode = 'multiple';
fixture.detectChanges(); fixture.detectChanges();
component.ngOnChanges({ preSelectGroups: change }); component.ngOnChanges({ preSelectGroups: change });
fixture.detectChanges(); fixture.detectChanges();
const chips = fixture.debugElement.queryAll(By.css('mat-chip-row'));
const chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toBe(2); expect(chips.length).toBe(2);
}); });
@@ -267,42 +245,40 @@ describe('GroupCloudComponent', () => {
const changedGroupsEmitterSpy = spyOn(component.changedGroups, 'emit'); const changedGroupsEmitterSpy = spyOn(component.changedGroups, 'emit');
component.mode = 'multiple'; component.mode = 'multiple';
const removeIcon = fixture.debugElement.query(By.css('mat-chip-row mat-icon')); const chip = await loader.getHarness(MatChipHarness);
removeIcon.nativeElement.click(); const icon = await chip.getHarness(MatIconHarness);
fixture.detectChanges(); await (await icon.host()).click();
await fixture.whenStable(); await fixture.whenStable();
expect(removeGroupEmitterSpy).toHaveBeenCalledWith(mockVegetableAubergine); expect(removeGroupEmitterSpy).toHaveBeenCalledWith(mockVegetableAubergine);
expect(changedGroupsEmitterSpy).toHaveBeenCalledWith([mockMeatChicken]); expect(changedGroupsEmitterSpy).toHaveBeenCalledWith([mockMeatChicken]);
expect(component.selectedGroups.indexOf({ expect(
component.selectedGroups.indexOf({
id: mockMeatChicken.id, id: mockMeatChicken.id,
name: mockMeatChicken.name name: mockMeatChicken.name
})).toEqual(-1); })
).toEqual(-1);
}); });
}); });
describe('Multiple Mode with read-only', () => { describe('Multiple Mode with read-only', () => {
it('Should not show remove icon for pre-selected groups if readonly property set to true', async () => { it('Should not show remove icon for pre-selected groups if readonly property set to true', async () => {
component.mode = 'multiple'; component.mode = 'multiple';
component.preSelectGroups = [ component.preSelectGroups = [{ id: mockVegetableAubergine.id, name: mockVegetableAubergine.name, readonly: true }, mockMeatChicken];
{ id: mockVegetableAubergine.id, name: mockVegetableAubergine.name, readonly: true },
mockMeatChicken
];
const changes = new SimpleChange(null, [{ name: mockVegetableAubergine.name }], false); const changes = new SimpleChange(null, [{ name: mockVegetableAubergine.name }], false);
component.ngOnChanges({ preSelectGroups: changes }); component.ngOnChanges({ preSelectGroups: changes });
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable(); await fixture.whenStable();
const chipList = fixture.nativeElement.querySelectorAll('mat-chip-grid mat-chip-row'); const chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toBe(2);
expect(chipList.length).toBe(2); const removeIconAubergine = element.querySelector(
const removeIconAubergine = getElement(`[data-automation-id="adf-cloud-group-chip-remove-icon-${mockVegetableAubergine.name}"]`); `[data-automation-id="adf-cloud-group-chip-remove-icon-${mockVegetableAubergine.name}"]`
);
expect(removeIconAubergine).toBeNull(); expect(removeIconAubergine).toBeNull();
const removeIconPepper = getElement(`[data-automation-id="adf-cloud-group-chip-remove-icon-${mockMeatChicken.name}"]`); const removeIconPepper = element.querySelector(`[data-automation-id="adf-cloud-group-chip-remove-icon-${mockMeatChicken.name}"]`);
expect(removeIconPepper).not.toBeNull(); expect(removeIconPepper).not.toBeNull();
}); });
it('Should be able to remove preselected groups if readonly property set to false', async () => { it('Should be able to remove preselected groups if readonly property set to false', async () => {
@@ -315,18 +291,17 @@ describe('GroupCloudComponent', () => {
const removeGroupSpy = spyOn(component.removeGroup, 'emit'); const removeGroupSpy = spyOn(component.removeGroup, 'emit');
fixture.detectChanges(); fixture.detectChanges();
fixture.whenStable(); let chips = await loader.getAllHarnesses(MatChipHarness);
fixture.detectChanges(); expect(chips.length).toBe(2);
const chipList = fixture.nativeElement.querySelectorAll('mat-chip-grid mat-chip-row'); const removeIcon = element.querySelector<HTMLElement>(`[data-automation-id="adf-cloud-group-chip-remove-icon-${mockMeatChicken.name}"]`);
expect(chipList.length).toBe(2);
const removeIcon = getElement(`[data-automation-id="adf-cloud-group-chip-remove-icon-${mockMeatChicken.name}"]`);
removeIcon.click(); removeIcon.click();
fixture.detectChanges(); fixture.detectChanges();
expect(removeGroupSpy).toHaveBeenCalled(); expect(removeGroupSpy).toHaveBeenCalled();
expect(fixture.nativeElement.querySelectorAll('mat-chip-grid mat-chip-row').length).toBe(1);
chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toBe(1);
}); });
it('should removeDuplicatedGroups return only unique groups', () => { it('should removeDuplicatedGroups return only unique groups', () => {
@@ -336,7 +311,6 @@ describe('GroupCloudComponent', () => {
}); });
describe('Preselected groups and validation enabled', () => { describe('Preselected groups and validation enabled', () => {
beforeEach(() => { beforeEach(() => {
spyOn(identityGroupService, 'search').and.throwError('Invalid group'); spyOn(identityGroupService, 'search').and.throwError('Invalid group');
component.validate = true; component.validate = true;
@@ -365,7 +339,7 @@ describe('GroupCloudComponent', () => {
describe('Component readonly mode', () => { describe('Component readonly mode', () => {
const change = new SimpleChange(null, mockFoodGroups, false); const change = new SimpleChange(null, mockFoodGroups, false);
it('should chip list be disabled and show one single chip - single mode', () => { it('should chip list be disabled and show one single chip - single mode', async () => {
component.mode = 'single'; component.mode = 'single';
component.readOnly = true; component.readOnly = true;
component.preSelectGroups = mockFoodGroups; component.preSelectGroups = mockFoodGroups;
@@ -373,16 +347,14 @@ describe('GroupCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
const chips = fixture.debugElement.queryAll(By.css('mat-chip-row')); const chips = await loader.getAllHarnesses(MatChipHarness);
const chipList = getElement('mat-chip-grid');
expect(chips).toBeDefined();
expect(chipList).toBeDefined();
expect(chips.length).toBe(1); expect(chips.length).toBe(1);
expect(chipList.attributes['ng-reflect-disabled']?.value).toEqual('true');
const chipList = await loader.getHarness(MatChipListHarness);
expect(await chipList.isDisabled()).toBe(true);
}); });
it('should chip list be disabled and show all the chips - multiple mode', () => { it('should chip list be disabled and show all the chips - multiple mode', async () => {
component.mode = 'multiple'; component.mode = 'multiple';
component.readOnly = true; component.readOnly = true;
component.preSelectGroups = mockFoodGroups; component.preSelectGroups = mockFoodGroups;
@@ -390,14 +362,11 @@ describe('GroupCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
const chips = fixture.debugElement.queryAll(By.css('mat-chip-row')); const chips = await loader.getAllHarnesses(MatChipHarness);
const chipList = getElement('mat-chip-grid');
expect(chips).toBeDefined();
expect(chipList).toBeDefined();
expect(chips.length).toBe(2); expect(chips.length).toBe(2);
expect(chipList.attributes['ng-reflect-disabled']?.value).toEqual('true');
});
});
const chipList = await loader.getHarness(MatChipListHarness);
expect(await chipList.isDisabled()).toBe(true);
});
});
}); });

View File

@@ -25,31 +25,19 @@ import { By } from '@angular/platform-browser';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { IdentityUserServiceInterface } from '../services/identity-user.service.interface'; import { IdentityUserServiceInterface } from '../services/identity-user.service.interface';
import { IDENTITY_USER_SERVICE_TOKEN } from '../services/identity-user-service.token'; import { IDENTITY_USER_SERVICE_TOKEN } from '../services/identity-user-service.token';
import { import { mockFoodUsers, mockKielbasaSausage, mockShepherdsPie, mockYorkshirePudding, mockPreselectedFoodUsers } from '../mock/people-cloud.mock';
mockFoodUsers, import { HarnessLoader } from '@angular/cdk/testing';
mockKielbasaSausage, import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
mockShepherdsPie, import { MatChipHarness, MatChipListHarness } from '@angular/material/chips/testing';
mockYorkshirePudding, import { MatInputHarness } from '@angular/material/input/testing';
mockPreselectedFoodUsers
} from '../mock/people-cloud.mock';
describe('PeopleCloudComponent', () => { describe('PeopleCloudComponent', () => {
let loader: HarnessLoader;
let component: PeopleCloudComponent; let component: PeopleCloudComponent;
let fixture: ComponentFixture<PeopleCloudComponent>; let fixture: ComponentFixture<PeopleCloudComponent>;
let element: HTMLElement; let element: HTMLElement;
let identityUserService: IdentityUserServiceInterface; let identityUserService: IdentityUserServiceInterface;
let searchSpy; let searchSpy: jasmine.Spy;
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions
/**
* get the native element by selector
*
* @param selector selector
* @returns native element
*/
function getElement<T = HTMLElement>(selector: string): T {
return fixture.nativeElement.querySelector(selector);
}
/** /**
* Search users by value * Search users by value
@@ -57,14 +45,9 @@ describe('PeopleCloudComponent', () => {
* @param value value * @param value value
*/ */
async function searchUsers(value: string) { async function searchUsers(value: string) {
const input = getElement<HTMLInputElement>('input'); const input = await loader.getHarness(MatInputHarness);
input.focus(); await input.focus();
input.value = value; await input.setValue(value);
input.dispatchEvent(new Event('keyup'));
input.dispatchEvent(new Event('input'));
await fixture.whenStable();
fixture.detectChanges();
} }
/** /**
@@ -73,17 +56,10 @@ describe('PeopleCloudComponent', () => {
* @param value value * @param value value
*/ */
async function searchUsersAndBlur(value: string) { async function searchUsersAndBlur(value: string) {
const input = getElement<HTMLInputElement>('input'); const input = await loader.getHarness(MatInputHarness);
input.focus(); await input.focus();
input.value = value; await input.setValue(value);
input.dispatchEvent(new Event('keyup')); await input.blur();
input.dispatchEvent(new Event('input'));
await fixture.whenStable();
fixture.detectChanges();
input.blur();
fixture.detectChanges();
} }
/** /**
@@ -95,15 +71,6 @@ describe('PeopleCloudComponent', () => {
return fixture.debugElement.queryAll(By.css('[data-automation-id="adf-people-cloud-row"]')); return fixture.debugElement.queryAll(By.css('[data-automation-id="adf-people-cloud-row"]'));
} }
/**
* Get users chip list UI
*
* @returns list of debug elements
*/
function getUsersChipsUI(): DebugElement[] {
return fixture.debugElement.queryAll(By.css('mat-chip-row'));
}
/** /**
* Get the first user from the list * Get the first user from the list
* *
@@ -119,15 +86,17 @@ describe('PeopleCloudComponent', () => {
}); });
fixture = TestBed.createComponent(PeopleCloudComponent); fixture = TestBed.createComponent(PeopleCloudComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
element = fixture.nativeElement;
identityUserService = TestBed.inject(IDENTITY_USER_SERVICE_TOKEN); identityUserService = TestBed.inject(IDENTITY_USER_SERVICE_TOKEN);
loader = TestbedHarnessEnvironment.loader(fixture);
}); });
it('should populate placeholder when title is present', () => { it('should populate placeholder when title is present', () => {
component.title = 'TITLE_KEY'; component.title = 'TITLE_KEY';
fixture.detectChanges(); fixture.detectChanges();
const matLabel = getElement<HTMLInputElement>('#adf-people-cloud-title-id'); const matLabel = element.querySelector<HTMLInputElement>('#adf-people-cloud-title-id');
expect(matLabel.textContent).toEqual('TITLE_KEY'); expect(matLabel.textContent).toEqual('TITLE_KEY');
}); });
@@ -135,7 +104,7 @@ describe('PeopleCloudComponent', () => {
it('should not populate placeholder when title is not present', () => { it('should not populate placeholder when title is not present', () => {
fixture.detectChanges(); fixture.detectChanges();
const matLabel = getElement<HTMLInputElement>('#adf-people-cloud-title-id'); const matLabel = element.querySelector<HTMLInputElement>('#adf-people-cloud-title-id');
expect(matLabel.textContent).toEqual(''); expect(matLabel.textContent).toEqual('');
}); });
@@ -190,7 +159,9 @@ describe('PeopleCloudComponent', () => {
}); });
it('should not be able to search for a user that his email matches one of the excluded users email', async () => { it('should not be able to search for a user that his email matches one of the excluded users email', async () => {
component.excludedUsers = [{ email: mockKielbasaSausage.email, username: 'new-username', firstName: 'new-first-name', lastName: 'new-last-name' }]; component.excludedUsers = [
{ email: mockKielbasaSausage.email, username: 'new-username', firstName: 'new-first-name', lastName: 'new-last-name' }
];
fixture.detectChanges(); fixture.detectChanges();
await searchUsers('first-name'); await searchUsers('first-name');
@@ -199,7 +170,15 @@ describe('PeopleCloudComponent', () => {
}); });
it('should not be able to search for a user that his id matches one of the excluded users id', async () => { it('should not be able to search for a user that his id matches one of the excluded users id', async () => {
component.excludedUsers = [{ id: mockKielbasaSausage.id, username: 'new-username', firstName: 'new-first-name', lastName: 'new-last-name', email: 'new-email@food.com' }]; component.excludedUsers = [
{
id: mockKielbasaSausage.id,
username: 'new-username',
firstName: 'new-first-name',
lastName: 'new-last-name',
email: 'new-email@food.com'
}
];
fixture.detectChanges(); fixture.detectChanges();
await searchUsers('first-name'); await searchUsers('first-name');
@@ -208,7 +187,9 @@ describe('PeopleCloudComponent', () => {
}); });
it('should not be able to search for a user that his username matches one of the excluded users username', async () => { it('should not be able to search for a user that his username matches one of the excluded users username', async () => {
component.excludedUsers = [{ username: mockKielbasaSausage.username, firstName: 'new-first-name', lastName: 'new-last-name', email: 'new-email@food.com' }]; component.excludedUsers = [
{ username: mockKielbasaSausage.username, firstName: 'new-first-name', lastName: 'new-last-name', email: 'new-email@food.com' }
];
fixture.detectChanges(); fixture.detectChanges();
await searchUsers('first-name'); await searchUsers('first-name');
@@ -295,17 +276,20 @@ describe('PeopleCloudComponent', () => {
}); });
describe('No preselected users', () => { describe('No preselected users', () => {
it('should not pre-select any user when preSelectUsers is empty - single mode', async () => {
it('should not pre-select any user when preSelectUsers is empty - single mode', () => {
component.mode = 'single'; component.mode = 'single';
fixture.detectChanges(); fixture.detectChanges();
expect(getUsersChipsUI().length).toEqual(0);
const chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toBe(0);
}); });
it('should not pre-select any users when preSelectUsers is empty - multiple mode', () => { it('should not pre-select any users when preSelectUsers is empty - multiple mode', async () => {
component.mode = 'multiple'; component.mode = 'multiple';
fixture.detectChanges(); fixture.detectChanges();
expect(getUsersChipsUI().length).toEqual(0);
const chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toEqual(0);
}); });
}); });
@@ -321,14 +305,16 @@ describe('PeopleCloudComponent', () => {
element = fixture.nativeElement; element = fixture.nativeElement;
}); });
it('should show only one mat chip with the first preSelectedUser', () => { it('should show only one mat chip with the first preSelectedUser', async () => {
expect(getUsersChipsUI().length).toEqual(1); const chips = await loader.getAllHarnesses(MatChipHarness);
expect(getUsersChipsUI()[0].attributes['data-automation-id']).toEqual(`adf-people-cloud-chip-${mockPreselectedFoodUsers[0].username}`); expect(chips.length).toEqual(1);
const testId = await (await chips[0].host()).getAttribute('data-automation-id');
expect(testId).toEqual(`adf-people-cloud-chip-${mockPreselectedFoodUsers[0].username}`);
}); });
}); });
describe('Multiple Mode with Pre-selected Users', () => { describe('Multiple Mode with Pre-selected Users', () => {
beforeEach(() => { beforeEach(() => {
component.mode = 'multiple'; component.mode = 'multiple';
}); });
@@ -341,9 +327,15 @@ describe('PeopleCloudComponent', () => {
await fixture.whenStable(); await fixture.whenStable();
fixture.detectChanges(); fixture.detectChanges();
expect(getUsersChipsUI().length).toEqual(2);
expect(getUsersChipsUI()[0].attributes['data-automation-id']).toEqual(`adf-people-cloud-chip-${mockPreselectedFoodUsers[0].username}`); const chips = await loader.getAllHarnesses(MatChipHarness);
expect(getUsersChipsUI()[1].attributes['data-automation-id']).toEqual(`adf-people-cloud-chip-${mockPreselectedFoodUsers[1].username}`); expect(chips.length).toEqual(2);
const testId1 = await (await chips[0].host()).getAttribute('data-automation-id');
const testId2 = await (await chips[1].host()).getAttribute('data-automation-id');
expect(testId1).toEqual(`adf-people-cloud-chip-${mockPreselectedFoodUsers[0].username}`);
expect(testId2).toEqual(`adf-people-cloud-chip-${mockPreselectedFoodUsers[1].username}`);
}); });
it('Should not show remove icon for pre-selected users if readonly property set to true', async () => { it('Should not show remove icon for pre-selected users if readonly property set to true', async () => {
@@ -355,12 +347,16 @@ describe('PeopleCloudComponent', () => {
const change = new SimpleChange(null, component.preSelectUsers, false); const change = new SimpleChange(null, component.preSelectUsers, false);
component.ngOnChanges({ preSelectUsers: change }); component.ngOnChanges({ preSelectUsers: change });
await fixture.whenStable();
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
const removeIcon = getElement(`[data-automation-id="adf-people-cloud-chip-remove-icon-${mockPreselectedFoodUsers[0].username}"]`); const removeIcon = element.querySelector(
`[data-automation-id="adf-people-cloud-chip-remove-icon-${mockPreselectedFoodUsers[0].username}"]`
);
const chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toBe(2);
expect(getUsersChipsUI().length).toBe(2);
expect(component.preSelectUsers[0].readonly).toBeTruthy(); expect(component.preSelectUsers[0].readonly).toBeTruthy();
expect(component.preSelectUsers[1].readonly).toBeTruthy(); expect(component.preSelectUsers[1].readonly).toBeTruthy();
expect(removeIcon).toBeNull(); expect(removeIcon).toBeNull();
@@ -374,27 +370,32 @@ describe('PeopleCloudComponent', () => {
const removeUserSpy = spyOn(component.removeUser, 'emit'); const removeUserSpy = spyOn(component.removeUser, 'emit');
await fixture.whenStable();
fixture.detectChanges(); fixture.detectChanges();
await fixture.whenStable();
const removeIcon = getElement(`[data-automation-id="adf-people-cloud-chip-remove-icon-${mockPreselectedFoodUsers[0].username}"]`); const removeIcon = element.querySelector<HTMLElement>(
`[data-automation-id="adf-people-cloud-chip-remove-icon-${mockPreselectedFoodUsers[0].username}"]`
);
expect(getUsersChipsUI().length).toBe(2); let chips = await loader.getAllHarnesses(MatChipHarness);
expect(component.preSelectUsers[0].readonly).toBe(false, 'Removable'); expect(chips.length).toBe(2);
expect(component.preSelectUsers[1].readonly).toBe(false, 'Removable');
expect(component.preSelectUsers[0].readonly).toBe(false);
expect(component.preSelectUsers[1].readonly).toBe(false);
removeIcon.click(); removeIcon.click();
fixture.detectChanges(); fixture.detectChanges();
expect(removeUserSpy).toHaveBeenCalled(); expect(removeUserSpy).toHaveBeenCalled();
expect(getUsersChipsUI().length).toBe(1);
chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toBe(1);
}); });
describe('Component readonly mode', () => { describe('Component readonly mode', () => {
const change = new SimpleChange(null, mockPreselectedFoodUsers, false); const change = new SimpleChange(null, mockPreselectedFoodUsers, false);
it('should chip list be disabled and show one single chip - single mode', () => { it('should chip list be disabled and show one single chip - single mode', async () => {
component.mode = 'single'; component.mode = 'single';
component.readOnly = true; component.readOnly = true;
component.preSelectUsers = mockPreselectedFoodUsers; component.preSelectUsers = mockPreselectedFoodUsers;
@@ -402,15 +403,14 @@ describe('PeopleCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
const chipList = getElement('mat-chip-grid'); const chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toBe(1);
expect(getUsersChipsUI()).toBeDefined(); const chipList = await loader.getHarness(MatChipListHarness);
expect(chipList).toBeDefined(); expect(await chipList.isDisabled()).toBe(true);
expect(getUsersChipsUI().length).toBe(1);
expect(chipList.attributes['ng-reflect-disabled'].value).toEqual('true');
}); });
it('should chip list be disabled and show mat chips for all the preselected users - multiple mode', () => { it('should chip list be disabled and show mat chips for all the preselected users - multiple mode', async () => {
component.mode = 'multiple'; component.mode = 'multiple';
component.readOnly = true; component.readOnly = true;
component.preSelectUsers = mockPreselectedFoodUsers; component.preSelectUsers = mockPreselectedFoodUsers;
@@ -418,18 +418,16 @@ describe('PeopleCloudComponent', () => {
fixture.detectChanges(); fixture.detectChanges();
const chipList = getElement('mat-chip-grid'); const chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toBe(2);
expect(getUsersChipsUI()).toBeDefined(); const chipList = await loader.getHarness(MatChipListHarness);
expect(chipList).toBeDefined(); expect(await chipList.isDisabled()).toBe(true);
expect(getUsersChipsUI().length).toBe(2);
expect(chipList.attributes['ng-reflect-disabled'].value).toEqual('true');
}); });
}); });
}); });
describe('Preselected users and validation enabled', () => { describe('Preselected users and validation enabled', () => {
beforeEach(() => { beforeEach(() => {
spyOn(identityUserService, 'search').and.throwError('Invalid user'); spyOn(identityUserService, 'search').and.throwError('Invalid user');
component.validate = true; component.validate = true;