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';
import { SearchFacetFiltersService } from '../../services/search-facet-filters.service';
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', () => {
let loader: HarnessLoader;
let fixture: ComponentFixture<SearchFilterComponent>;
let component: SearchFilterComponent;
let queryBuilder: SearchQueryBuilderService;
@@ -60,8 +67,9 @@ describe('SearchFilterComponent', () => {
fixture = TestBed.createComponent(SearchFilterComponent);
appConfigService = TestBed.inject(AppConfigService);
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;
loader = TestbedHarnessEnvironment.loader(fixture);
});
afterEach(() => fixture.destroy());
@@ -73,27 +81,41 @@ describe('SearchFilterComponent', () => {
spyOn(queryBuilder, 'execute').and.stub();
queryBuilder.config = {
categories: [],
facetFields: { fields: [
facetFields: {
fields: [
{ label: 'f1', field: 'f1' },
{ label: 'f2', field: 'f2' }
]},
]
},
facetQueries: {
queries: []
}
};
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: 'b2', count: 1, filterQuery: 'filter2' }]) },
{ label: 'b2', count: 1, filterQuery: 'filter2' }
])
},
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList([]) }
];
queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]);
const serverResponseFields: any = [
{ type: 'field', label: 'f1', field: 'f1', buckets: [
{ label: 'b1', metrics: [{value: {count: 6}}], filterQuery: 'filter' },
{ label: 'b2', metrics: [{value: {count: 1}}], filterQuery: 'filter2' }] },
{
type: 'field',
label: 'f1',
field: 'f1',
buckets: [
{ label: 'b1', metrics: [{ value: { count: 6 } }], filterQuery: 'filter' },
{ label: 'b2', metrics: [{ value: { count: 1 } }], filterQuery: 'filter2' }
]
},
{ type: 'field', label: 'f2', field: 'f2', buckets: [] }
];
const data = {
@@ -117,27 +139,41 @@ describe('SearchFilterComponent', () => {
spyOn(queryBuilder, 'execute').and.stub();
queryBuilder.config = {
categories: [],
facetFields: { fields: [
facetFields: {
fields: [
{ label: 'f1', field: 'f1' },
{ label: 'f2', field: 'f2' }
]},
]
},
facetQueries: {
queries: []
}
};
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: 'b2', count: 1, filterQuery: 'filter2' }]) },
{ label: 'b2', count: 1, filterQuery: 'filter2' }
])
},
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList([]) }
];
queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]);
const serverResponseFields: any = [
{ type: 'field', label: 'f1', field: 'f1', buckets: [
{ label: 'b1', metrics: [{value: {count: 6}}], filterQuery: 'filter' },
{ label: 'b2', metrics: [{value: {count: 1}}], filterQuery: 'filter2' }] },
{
type: 'field',
label: 'f1',
field: 'f1',
buckets: [
{ label: 'b1', metrics: [{ value: { count: 6 } }], filterQuery: 'filter' },
{ label: 'b2', metrics: [{ value: { count: 1 } }], filterQuery: 'filter2' }
]
},
{ type: 'field', label: 'f2', field: 'f2', buckets: [] }
];
const data = {
@@ -161,19 +197,27 @@ describe('SearchFilterComponent', () => {
spyOn(queryBuilder, 'execute').and.stub();
queryBuilder.config = {
categories: [],
facetFields: { fields: [
facetFields: {
fields: [
{ label: 'f1', field: 'f1' },
{ label: 'f2', field: 'f2' }
]},
]
},
facetQueries: {
queries: []
}
};
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: 'b2', count: 1, filterQuery: 'filter2' }]) },
{ label: 'b2', count: 1, filterQuery: 'filter2' }
])
},
{ type: 'field', label: 'f2', field: 'f2', buckets: new SearchFilterList() }
];
queryBuilder.addUserFacetBucket('f1', searchFacetFiltersService.responseFacets[0].buckets.items[0]);
@@ -199,9 +243,10 @@ describe('SearchFilterComponent', () => {
const queryResponse = {
label: 'query response',
buckets: new SearchFilterList([
{ label: 'q1', query: 'q1', checked: true, 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: 'q1', query: 'q1', checked: true, metrics: [{ value: { count: 1 } }] },
{ label: 'q2', query: 'q2', checked: false, metrics: [{ value: { count: 1 } }] },
{ label: 'q3', query: 'q3', checked: true, metrics: [{ value: { count: 1 } }] }
])
} as any;
searchFacetFiltersService.responseFacets = [queryResponse];
@@ -219,7 +264,6 @@ describe('SearchFilterComponent', () => {
});
describe('widgets', () => {
it('should have expandable categories', async () => {
fixture.detectChanges();
await fixture.whenStable();
@@ -229,24 +273,8 @@ describe('SearchFilterComponent', () => {
fixture.detectChanges();
await fixture.whenStable();
const panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel'));
const panels = await loader.getAllHarnesses(MatExpansionPanelHarness);
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 () => {
@@ -256,7 +284,7 @@ describe('SearchFilterComponent', () => {
fixture.detectChanges();
await fixture.whenStable();
const panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel'));
const panels = await loader.getAllHarnesses(MatExpansionPanelHarness);
expect(panels.length).toBe(0);
});
@@ -267,21 +295,11 @@ describe('SearchFilterComponent', () => {
fixture.detectChanges();
await fixture.whenStable();
const panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel'));
const panels = await loader.getAllHarnesses(MatExpansionPanelHarness);
expect(panels.length).toBe(1);
const title = fixture.debugElement.query(By.css('.mat-expansion-panel-header-title'));
expect(title.nativeElement.innerText.trim()).toBe('Type');
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);
expect(await panels[0].getTitle()).toBe('Type');
expect(await panels[0].isExpanded()).toBe(true);
});
it('should show the widgets only if configured', async () => {
@@ -291,11 +309,11 @@ describe('SearchFilterComponent', () => {
fixture.detectChanges();
await fixture.whenStable();
const panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel'));
const panels = await loader.getAllHarnesses(MatExpansionPanelHarness);
expect(panels.length).toBe(2);
const titleElements = fixture.debugElement.queryAll(By.css('.mat-expansion-panel-header-title'));
expect(titleElements.map(title => title.nativeElement.innerText.trim())).toEqual(['Name', 'Type']);
expect(await panels[0].getTitle()).toBe('Name');
expect(await panels[1].getTitle()).toBe('Type');
});
it('should be update the search query when name changed', async () => {
@@ -305,17 +323,19 @@ describe('SearchFilterComponent', () => {
fixture.detectChanges();
await fixture.whenStable();
let panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel'));
let panels = await loader.getAllHarnesses(MatExpansionPanelHarness);
expect(panels.length).toBe(6);
const inputElement = fixture.debugElement.query(By.css('[data-automation-id="expansion-panel-Name"] input'));
inputElement.triggerEventHandler('change', { target: { value: '*' } });
expect(queryBuilder.update).toHaveBeenCalled();
queryBuilder.executed.next(mockSearchResult);
fixture.detectChanges();
panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel'));
panels = await loader.getAllHarnesses(MatExpansionPanelHarness);
expect(panels.length).toBe(8);
});
@@ -326,19 +346,20 @@ describe('SearchFilterComponent', () => {
fixture.detectChanges();
await fixture.whenStable();
const inputElement = fixture.debugElement.query(By.css('[data-automation-id="expansion-panel-Name"] input'));
inputElement.triggerEventHandler('change', { target: { value: '*' } });
const input = await loader.getHarness(MatInputHarness);
await input.setValue('*');
queryBuilder.executed.next(getMockSearchResultWithResponseBucket());
fixture.detectChanges();
const panels = fixture.debugElement.queryAll(By.css('.mat-expansion-panel'));
const panels = await loader.getAllHarnesses(MatExpansionPanelHarness);
expect(panels.length).toBe(9);
});
it('should show the long facet options list with pagination', () => {
const panel = '[data-automation-id="expansion-panel-Size facet queries"]';
it('should show the long facet options list with pagination', async () => {
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;
queryBuilder.resetToDefaults();
@@ -346,58 +367,51 @@ describe('SearchFilterComponent', () => {
queryBuilder.executed.next(mockSearchResult);
fixture.detectChanges();
let sizes = getAllMenus(`${panel} mat-checkbox`, fixture);
expect(sizes).toEqual(stepOne);
const panel = await loader.getHarness(
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 lessButton = fixture.debugElement.query(By.css(`${panel} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`));
let sizes = await panel.getAllHarnesses(MatCheckboxHarness);
let sizeLabels = await Promise.all(sizes.map((element) => element.getLabelText()));
expect(sizeLabels).toEqual(stepOne);
expect(lessButton).toEqual(null);
expect(moreButton).toBeDefined();
let moreButton = await loader.getHarness(showMoreButton);
expect(await loader.hasHarness(showLessButton)).toBe(false);
moreButton.triggerEventHandler('click', {});
fixture.detectChanges();
await moreButton.click();
sizes = getAllMenus(`${panel} mat-checkbox`, fixture);
expect(sizes).toEqual(stepTwo);
sizes = await panel.getAllHarnesses(MatCheckboxHarness);
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"]`));
lessButton = fixture.debugElement.query(By.css(`${panel} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`));
expect(lessButton).toBeDefined();
expect(moreButton).toBeDefined();
moreButton = await loader.getHarness(showMoreButton);
expect(await loader.hasHarness(showLessButton)).toBe(true);
await moreButton.click();
moreButton.triggerEventHandler('click', {});
fixture.detectChanges();
sizes = getAllMenus(`${panel} mat-checkbox`, fixture);
sizes = await panel.getAllHarnesses(MatCheckboxHarness);
sizeLabels = await Promise.all(sizes.map((element) => element.getLabelText()));
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"]`));
lessButton = fixture.debugElement.query(By.css(`${panel} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`));
expect(lessButton).toBeDefined();
expect(moreButton).toEqual(null);
sizes = await panel.getAllHarnesses(MatCheckboxHarness);
sizeLabels = await Promise.all(sizes.map((element) => element.getLabelText()));
expect(sizeLabels).toEqual(stepTwo);
lessButton.triggerEventHandler('click', {});
fixture.detectChanges();
expect(await loader.hasHarness(showMoreButton)).toBe(true);
lessButton = await loader.getHarness(showLessButton);
await lessButton.click();
sizes = getAllMenus(`${panel} mat-checkbox`, fixture);
expect(sizes).toEqual(stepTwo);
sizes = await panel.getAllHarnesses(MatCheckboxHarness);
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"]`));
lessButton = fixture.debugElement.query(By.css(`${panel} button[title="SEARCH.FILTER.ACTIONS.SHOW-LESS"]`));
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();
expect(await loader.hasHarness(showMoreButton)).toBe(true);
expect(await loader.hasHarness(showLessButton)).toBe(false);
});
it('should not show facets if filter is not available', () => {
@@ -416,8 +430,8 @@ describe('SearchFilterComponent', () => {
expect(facetElement).toEqual(null);
});
it('should search the facets options and select it', () => {
const panel = '[data-automation-id="expansion-panel-Size facet queries"]';
it('should search the facets options and select it', async () => {
const panelSelector = '[data-automation-id="expansion-panel-Size facet queries"]';
appConfigService.config.search = searchFilter;
queryBuilder.resetToDefaults();
fixture.detectChanges();
@@ -426,41 +440,39 @@ describe('SearchFilterComponent', () => {
spyOn(queryBuilder, 'update').and.stub();
const inputElement = fixture.debugElement.query(By.css(`${panel} input`));
inputElement.nativeElement.value = 'Extra';
inputElement.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
const panel = await loader.getHarness(
MatExpansionPanelHarness.with({
selector: panelSelector
})
);
let filteredMenu = getAllMenus(`${panel} mat-checkbox`, fixture);
expect(filteredMenu).toEqual(['Extra Small (10239)']);
const input = await panel.getHarness(MatInputHarness);
await input.setValue('Extra');
inputElement.nativeElement.value = 'my';
inputElement.nativeElement.dispatchEvent(new Event('input'));
fixture.detectChanges();
let checkboxes = await panel.getAllHarnesses(MatCheckboxHarness);
expect(checkboxes.length).toBe(1);
expect(await checkboxes[0].getLabelText()).toBe('Extra Small (10239)');
filteredMenu = getAllMenus(`${panel} mat-checkbox`, fixture);
expect(filteredMenu).toEqual(filteredResult);
await input.setValue('my');
const clearButton = fixture.debugElement.query(By.css(`${panel} mat-form-field button`));
clearButton.triggerEventHandler('click', {});
fixture.detectChanges();
checkboxes = await panel.getAllHarnesses(MatCheckboxHarness);
let labels = await Promise.all(checkboxes.map((element) => element.getLabelText()));
expect(labels).toEqual(filteredResult);
filteredMenu = getAllMenus(`${panel} mat-checkbox`, fixture);
expect(filteredMenu).toEqual(stepOne);
const clearButton = await panel.getHarness(MatButtonHarness.with({ selector: '[title="SEARCH.FILTER.BUTTONS.CLEAR"]' }));
await clearButton.click();
const firstOption = fixture.debugElement.query(By.css(`${panel} mat-checkbox`));
firstOption.triggerEventHandler('change', { checked: true });
fixture.detectChanges();
const checkedOption = fixture.debugElement.query(By.css(`${panel} mat-checkbox.mat-mdc-checkbox-checked`));
expect(checkedOption.nativeElement.innerText).toEqual('Extra Small (10239)');
checkboxes = await panel.getAllHarnesses(MatCheckboxHarness);
labels = await Promise.all(checkboxes.map((element) => element.getLabelText()));
expect(labels).toEqual(stepOne);
await checkboxes[0].check();
expect(queryBuilder.update).toHaveBeenCalledTimes(1);
});
it('should preserve the filter state if other fields edited', () => {
const panel1 = '[data-automation-id="expansion-panel-Size facet queries"]';
const panel2 = '[data-automation-id="expansion-panel-Type facet queries"]';
it('should preserve the filter state if other fields edited', async () => {
const panel1Selector = '[data-automation-id="expansion-panel-Size facet queries"]';
const panel2selector = '[data-automation-id="expansion-panel-Type facet queries"]';
appConfigService.config.search = searchFilter;
queryBuilder.resetToDefaults();
fixture.detectChanges();
@@ -468,39 +480,39 @@ describe('SearchFilterComponent', () => {
fixture.detectChanges();
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.dispatchEvent(new Event('input'));
fixture.detectChanges();
let filteredMenu = getAllMenus(`${panel1} mat-checkbox`, fixture);
expect(filteredMenu).toEqual(filteredResult);
const panel1 = await loader.getHarness(MatExpansionPanelHarness.with({ selector: panel1Selector }));
const firstOption = fixture.debugElement.query(By.css(`${panel1} mat-checkbox`));
firstOption.triggerEventHandler('change', { checked: true });
fixture.detectChanges();
let checkboxes = await panel1.getAllHarnesses(MatCheckboxHarness);
let labels = await Promise.all(checkboxes.map((element) => element.getLabelText()));
expect(labels).toEqual(filteredResult);
let panel1CheckedOption = fixture.debugElement.query(By.css(`${panel1} mat-checkbox.mat-mdc-checkbox-checked`));
expect(panel1CheckedOption.nativeElement.innerText).toEqual('my1 (806)');
await checkboxes[0].check();
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`));
panel2Options.triggerEventHandler('change', { checked: true });
fixture.detectChanges();
const panel2 = await loader.getHarness(MatExpansionPanelHarness.with({ selector: panel2selector }));
checkboxes = await panel2.getAllHarnesses(MatCheckboxHarness);
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`));
expect(panel2CheckedOption.nativeElement.innerText).toEqual('SEARCH.FACET_QUERIES.MIMETYPE (13)');
checkboxes = await panel1.getAllHarnesses(MatCheckboxHarness);
labels = await Promise.all(checkboxes.map((element) => element.getLabelText()));
expect(labels).toEqual(filteredResult);
filteredMenu = getAllMenus(`${panel1} mat-checkbox`, fixture);
expect(filteredMenu).toEqual(filteredResult);
panel1CheckedOption = fixture.debugElement.query(By.css(`${panel1} mat-checkbox.mat-mdc-checkbox-checked`));
expect(panel1CheckedOption.nativeElement.innerText).toEqual('my1 (806)');
const checkedOption = await panel1.getHarness(MatCheckboxHarness.with({ checked: true }));
expect(await checkedOption.getLabelText()).toBe('my1 (806)');
expect(queryBuilder.update).toHaveBeenCalledTimes(2);
});
it('should reset the query fragments when reset All is clicked', () => {
component.queryBuilder.queryFragments = { fragment1 : 'value1'};
component.queryBuilder.queryFragments = { fragment1: 'value1' };
appConfigService.config.search = searchFilter;
searchFacetFiltersService.responseFacets = [];
component.displayResetButton = true;
@@ -513,11 +525,10 @@ describe('SearchFilterComponent', () => {
expect(component.queryBuilder.queryFragments).toEqual({});
expect(queryBuilder.resetToDefaults).toHaveBeenCalled();
});
});
});
export const getAllMenus = (regex, fixture: ComponentFixture<any>): string[] => {
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 { By } from '@angular/platform-browser';
import { of } from 'rxjs';
import { ProcessServiceCloudTestingModule } from './../../testing/process-service-cloud.testing.module';
import { GroupCloudModule } from '../group-cloud.module';
import { GroupCloudComponent } from './group-cloud.component';
import { CoreTestingModule } from '@alfresco/adf-core';
import { DebugElement, SimpleChange } from '@angular/core';
import { IdentityGroupService } from '../services/identity-group.service';
import { mockFoodGroups, mockMeatChicken, mockVegetableAubergine } from '../mock/group-cloud.mock';
import { TranslationMock, TranslationService } from '@alfresco/adf-core';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { HarnessLoader } from '@angular/cdk/testing';
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', () => {
let loader: HarnessLoader;
let component: GroupCloudComponent;
let fixture: ComponentFixture<GroupCloudComponent>;
let element: HTMLElement;
let identityGroupService: IdentityGroupService;
let findGroupsByNameSpy;
// 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);
}
let findGroupsByNameSpy: jasmine.Spy;
/**
* search group by value
@@ -50,14 +45,9 @@ describe('GroupCloudComponent', () => {
* @param value element input value
*/
async function searchGroup(value: string) {
const input = getElement<HTMLInputElement>('input');
input.focus();
input.value = value;
input.dispatchEvent(new Event('keyup'));
input.dispatchEvent(new Event('input'));
await fixture.whenStable();
fixture.detectChanges();
const input = await loader.getHarness(MatInputHarness);
await input.focus();
await input.setValue(value);
}
/**
@@ -66,17 +56,10 @@ describe('GroupCloudComponent', () => {
* @param value value
*/
async function searchGroupsAndBlur(value: string) {
const input = getElement<HTMLInputElement>('input');
input.focus();
input.value = value;
input.dispatchEvent(new Event('keyup'));
input.dispatchEvent(new Event('input'));
await fixture.whenStable();
fixture.detectChanges();
input.blur();
fixture.detectChanges();
const input = await loader.getHarness(MatInputHarness);
await input.focus();
await input.setValue(value);
await input.blur();
}
/**
@@ -90,20 +73,14 @@ describe('GroupCloudComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot(),
NoopAnimationsModule,
GroupCloudModule
],
providers: [
{ provide: TranslationService, useClass: TranslationMock }
]
imports: [TranslateModule.forRoot(), CoreTestingModule, ProcessServiceCloudTestingModule, GroupCloudModule]
});
fixture = TestBed.createComponent(GroupCloudComponent);
component = fixture.componentInstance;
element = fixture.nativeElement;
identityGroupService = TestBed.inject(IdentityGroupService);
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should populate placeholder when title is present', () => {
@@ -116,7 +93,6 @@ describe('GroupCloudComponent', () => {
});
describe('Search group', () => {
beforeEach(() => {
fixture.detectChanges();
findGroupsByNameSpy = spyOn(identityGroupService, 'search').and.returnValue(of(mockFoodGroups));
@@ -209,19 +185,19 @@ describe('GroupCloudComponent', () => {
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';
fixture.detectChanges();
const chips = fixture.debugElement.queryAll(By.css('mat-chip'));
const chips = await loader.getAllHarnesses(MatChipHarness);
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';
fixture.detectChanges();
const chips = fixture.debugElement.queryAll(By.css('mat-chip'));
const chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toEqual(0);
});
});
@@ -236,10 +212,11 @@ describe('GroupCloudComponent', () => {
fixture.detectChanges();
});
it('should show only one mat chip with the first preSelectedGroup', () => {
const chips = fixture.debugElement.queryAll(By.css('mat-chip-row'));
it('should show only one mat chip with the first preSelectedGroup', async () => {
const chips = await loader.getAllHarnesses(MatChipHarness);
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();
});
it('should render all preselected groups', () => {
it('should render all preselected groups', async () => {
component.mode = 'multiple';
fixture.detectChanges();
component.ngOnChanges({ preSelectGroups: change });
fixture.detectChanges();
const chips = fixture.debugElement.queryAll(By.css('mat-chip-row'));
const chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toBe(2);
});
@@ -267,42 +245,40 @@ describe('GroupCloudComponent', () => {
const changedGroupsEmitterSpy = spyOn(component.changedGroups, 'emit');
component.mode = 'multiple';
const removeIcon = fixture.debugElement.query(By.css('mat-chip-row mat-icon'));
removeIcon.nativeElement.click();
fixture.detectChanges();
const chip = await loader.getHarness(MatChipHarness);
const icon = await chip.getHarness(MatIconHarness);
await (await icon.host()).click();
await fixture.whenStable();
expect(removeGroupEmitterSpy).toHaveBeenCalledWith(mockVegetableAubergine);
expect(changedGroupsEmitterSpy).toHaveBeenCalledWith([mockMeatChicken]);
expect(component.selectedGroups.indexOf({
expect(
component.selectedGroups.indexOf({
id: mockMeatChicken.id,
name: mockMeatChicken.name
})).toEqual(-1);
})
).toEqual(-1);
});
});
describe('Multiple Mode with read-only', () => {
it('Should not show remove icon for pre-selected groups if readonly property set to true', async () => {
component.mode = 'multiple';
component.preSelectGroups = [
{ id: mockVegetableAubergine.id, name: mockVegetableAubergine.name, readonly: true },
mockMeatChicken
];
component.preSelectGroups = [{ id: mockVegetableAubergine.id, name: mockVegetableAubergine.name, readonly: true }, mockMeatChicken];
const changes = new SimpleChange(null, [{ name: mockVegetableAubergine.name }], false);
component.ngOnChanges({ preSelectGroups: changes });
fixture.detectChanges();
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 = getElement(`[data-automation-id="adf-cloud-group-chip-remove-icon-${mockVegetableAubergine.name}"]`);
const removeIconAubergine = element.querySelector(
`[data-automation-id="adf-cloud-group-chip-remove-icon-${mockVegetableAubergine.name}"]`
);
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();
});
it('Should be able to remove preselected groups if readonly property set to false', async () => {
@@ -315,28 +291,26 @@ describe('GroupCloudComponent', () => {
const removeGroupSpy = spyOn(component.removeGroup, 'emit');
fixture.detectChanges();
fixture.whenStable();
fixture.detectChanges();
let chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toBe(2);
const chipList = fixture.nativeElement.querySelectorAll('mat-chip-grid mat-chip-row');
expect(chipList.length).toBe(2);
const removeIcon = getElement(`[data-automation-id="adf-cloud-group-chip-remove-icon-${mockMeatChicken.name}"]`);
const removeIcon = element.querySelector<HTMLElement>(`[data-automation-id="adf-cloud-group-chip-remove-icon-${mockMeatChicken.name}"]`);
removeIcon.click();
fixture.detectChanges();
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', () => {
const duplicatedGroups = [ mockMeatChicken, mockMeatChicken];
const duplicatedGroups = [mockMeatChicken, mockMeatChicken];
expect(component.removeDuplicatedGroups(duplicatedGroups)).toEqual([mockMeatChicken]);
});
});
describe('Preselected groups and validation enabled', () => {
beforeEach(() => {
spyOn(identityGroupService, 'search').and.throwError('Invalid group');
component.validate = true;
@@ -365,7 +339,7 @@ describe('GroupCloudComponent', () => {
describe('Component readonly mode', () => {
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.readOnly = true;
component.preSelectGroups = mockFoodGroups;
@@ -373,16 +347,14 @@ describe('GroupCloudComponent', () => {
fixture.detectChanges();
const chips = fixture.debugElement.queryAll(By.css('mat-chip-row'));
const chipList = getElement('mat-chip-grid');
expect(chips).toBeDefined();
expect(chipList).toBeDefined();
const chips = await loader.getAllHarnesses(MatChipHarness);
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.readOnly = true;
component.preSelectGroups = mockFoodGroups;
@@ -390,14 +362,11 @@ describe('GroupCloudComponent', () => {
fixture.detectChanges();
const chips = fixture.debugElement.queryAll(By.css('mat-chip-row'));
const chipList = getElement('mat-chip-grid');
expect(chips).toBeDefined();
expect(chipList).toBeDefined();
const chips = await loader.getAllHarnesses(MatChipHarness);
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 { IdentityUserServiceInterface } from '../services/identity-user.service.interface';
import { IDENTITY_USER_SERVICE_TOKEN } from '../services/identity-user-service.token';
import {
mockFoodUsers,
mockKielbasaSausage,
mockShepherdsPie,
mockYorkshirePudding,
mockPreselectedFoodUsers
} from '../mock/people-cloud.mock';
import { mockFoodUsers, mockKielbasaSausage, mockShepherdsPie, mockYorkshirePudding, mockPreselectedFoodUsers } from '../mock/people-cloud.mock';
import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatChipHarness, MatChipListHarness } from '@angular/material/chips/testing';
import { MatInputHarness } from '@angular/material/input/testing';
describe('PeopleCloudComponent', () => {
let loader: HarnessLoader;
let component: PeopleCloudComponent;
let fixture: ComponentFixture<PeopleCloudComponent>;
let element: HTMLElement;
let identityUserService: IdentityUserServiceInterface;
let searchSpy;
// 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);
}
let searchSpy: jasmine.Spy;
/**
* Search users by value
@@ -57,14 +45,9 @@ describe('PeopleCloudComponent', () => {
* @param value value
*/
async function searchUsers(value: string) {
const input = getElement<HTMLInputElement>('input');
input.focus();
input.value = value;
input.dispatchEvent(new Event('keyup'));
input.dispatchEvent(new Event('input'));
await fixture.whenStable();
fixture.detectChanges();
const input = await loader.getHarness(MatInputHarness);
await input.focus();
await input.setValue(value);
}
/**
@@ -73,17 +56,10 @@ describe('PeopleCloudComponent', () => {
* @param value value
*/
async function searchUsersAndBlur(value: string) {
const input = getElement<HTMLInputElement>('input');
input.focus();
input.value = value;
input.dispatchEvent(new Event('keyup'));
input.dispatchEvent(new Event('input'));
await fixture.whenStable();
fixture.detectChanges();
input.blur();
fixture.detectChanges();
const input = await loader.getHarness(MatInputHarness);
await input.focus();
await input.setValue(value);
await input.blur();
}
/**
@@ -95,15 +71,6 @@ describe('PeopleCloudComponent', () => {
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
*
@@ -119,15 +86,17 @@ describe('PeopleCloudComponent', () => {
});
fixture = TestBed.createComponent(PeopleCloudComponent);
component = fixture.componentInstance;
element = fixture.nativeElement;
identityUserService = TestBed.inject(IDENTITY_USER_SERVICE_TOKEN);
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should populate placeholder when title is present', () => {
component.title = 'TITLE_KEY';
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');
});
@@ -135,7 +104,7 @@ describe('PeopleCloudComponent', () => {
it('should not populate placeholder when title is not present', () => {
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('');
});
@@ -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 () => {
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();
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 () => {
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();
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 () => {
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();
await searchUsers('first-name');
@@ -295,17 +276,20 @@ describe('PeopleCloudComponent', () => {
});
describe('No preselected users', () => {
it('should not pre-select any user when preSelectUsers is empty - single mode', () => {
it('should not pre-select any user when preSelectUsers is empty - single mode', async () => {
component.mode = 'single';
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';
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;
});
it('should show only one mat chip with the first preSelectedUser', () => {
expect(getUsersChipsUI().length).toEqual(1);
expect(getUsersChipsUI()[0].attributes['data-automation-id']).toEqual(`adf-people-cloud-chip-${mockPreselectedFoodUsers[0].username}`);
it('should show only one mat chip with the first preSelectedUser', async () => {
const chips = await loader.getAllHarnesses(MatChipHarness);
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', () => {
beforeEach(() => {
component.mode = 'multiple';
});
@@ -341,9 +327,15 @@ describe('PeopleCloudComponent', () => {
await fixture.whenStable();
fixture.detectChanges();
expect(getUsersChipsUI().length).toEqual(2);
expect(getUsersChipsUI()[0].attributes['data-automation-id']).toEqual(`adf-people-cloud-chip-${mockPreselectedFoodUsers[0].username}`);
expect(getUsersChipsUI()[1].attributes['data-automation-id']).toEqual(`adf-people-cloud-chip-${mockPreselectedFoodUsers[1].username}`);
const chips = await loader.getAllHarnesses(MatChipHarness);
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 () => {
@@ -355,12 +347,16 @@ describe('PeopleCloudComponent', () => {
const change = new SimpleChange(null, component.preSelectUsers, false);
component.ngOnChanges({ preSelectUsers: change });
await fixture.whenStable();
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[1].readonly).toBeTruthy();
expect(removeIcon).toBeNull();
@@ -374,27 +370,32 @@ describe('PeopleCloudComponent', () => {
const removeUserSpy = spyOn(component.removeUser, 'emit');
await fixture.whenStable();
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);
expect(component.preSelectUsers[0].readonly).toBe(false, 'Removable');
expect(component.preSelectUsers[1].readonly).toBe(false, 'Removable');
let chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toBe(2);
expect(component.preSelectUsers[0].readonly).toBe(false);
expect(component.preSelectUsers[1].readonly).toBe(false);
removeIcon.click();
fixture.detectChanges();
expect(removeUserSpy).toHaveBeenCalled();
expect(getUsersChipsUI().length).toBe(1);
chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toBe(1);
});
describe('Component readonly mode', () => {
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.readOnly = true;
component.preSelectUsers = mockPreselectedFoodUsers;
@@ -402,15 +403,14 @@ describe('PeopleCloudComponent', () => {
fixture.detectChanges();
const chipList = getElement('mat-chip-grid');
const chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toBe(1);
expect(getUsersChipsUI()).toBeDefined();
expect(chipList).toBeDefined();
expect(getUsersChipsUI().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 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.readOnly = true;
component.preSelectUsers = mockPreselectedFoodUsers;
@@ -418,18 +418,16 @@ describe('PeopleCloudComponent', () => {
fixture.detectChanges();
const chipList = getElement('mat-chip-grid');
const chips = await loader.getAllHarnesses(MatChipHarness);
expect(chips.length).toBe(2);
expect(getUsersChipsUI()).toBeDefined();
expect(chipList).toBeDefined();
expect(getUsersChipsUI().length).toBe(2);
expect(chipList.attributes['ng-reflect-disabled'].value).toEqual('true');
const chipList = await loader.getHarness(MatChipListHarness);
expect(await chipList.isDisabled()).toBe(true);
});
});
});
describe('Preselected users and validation enabled', () => {
beforeEach(() => {
spyOn(identityUserService, 'search').and.throwError('Invalid user');
component.validate = true;