Add whitespace error and fix unit test for checkbox

This commit is contained in:
Shivangi917
2025-07-28 08:04:44 -04:00
parent 029e824d87
commit 718f0be23c
10 changed files with 180 additions and 65 deletions
+2 -1
View File
@@ -575,7 +575,8 @@
"FOLDERS": "Folders", "FOLDERS": "Folders",
"LIBRARIES": "Libraries", "LIBRARIES": "Libraries",
"HINT": "Search input must have at least 2 alphanumeric characters.", "HINT": "Search input must have at least 2 alphanumeric characters.",
"REQUIRED": "Search term is required." "REQUIRED": "Search input is required.",
"WHITESPACE": "Search input cannot be only whitespace."
}, },
"SORT": { "SORT": {
"SORTING_OPTION": "Sort by", "SORTING_OPTION": "Sort by",
@@ -0,0 +1,50 @@
/*!
* Copyright © 2005-2025 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Alfresco Example Content Application
*
* This file is part of the Alfresco Example Content Application.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* The Alfresco Example Content Application is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The Alfresco Example Content Application is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* from Hyland Software. If not, see <http://www.gnu.org/licenses/>.
*/
import { FormControl } from '@angular/forms';
import { noWhitespaceValidator } from './no-whitespace.validator';
describe('noWhitespaceValidator', () => {
const validatorFn = noWhitespaceValidator();
it('should return null for valid non-whitespace input', () => {
const control = new FormControl('valid input');
expect(validatorFn(control)).toBeNull();
});
it('should return error for input with only spaces', () => {
const control = new FormControl(' ');
expect(validatorFn(control)).toEqual({ whitespace: true });
});
it('should return error for empty string', () => {
const control = new FormControl('');
expect(validatorFn(control)).toBeNull();
});
it('should return null for input with leading and trailing spaces but valid content inside', () => {
const control = new FormControl(' valid ');
expect(validatorFn(control)).toBeNull();
});
});
@@ -0,0 +1,37 @@
/*!
* Copyright © 2005-2025 Hyland Software, Inc. and its affiliates. All rights reserved.
*
* Alfresco Example Content Application
*
* This file is part of the Alfresco Example Content Application.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* The Alfresco Example Content Application is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The Alfresco Example Content Application is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* from Hyland Software. If not, see <http://www.gnu.org/licenses/>.
*/
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export const noWhitespaceValidator = (): ValidatorFn => {
return (control: AbstractControl): ValidationErrors | null => {
const rawValue = control.value;
if (rawValue === null || rawValue === '') {
return null;
}
const trimmedValue = rawValue.toString().trim();
return trimmedValue.length === 0 ? { whitespace: true } : null;
};
};
@@ -20,7 +20,6 @@
id="app-control-input" id="app-control-input"
[formControl]="searchFieldFormControl" [formControl]="searchFieldFormControl"
(keydown.enter)="searchSubmit()" (keydown.enter)="searchSubmit()"
(blur)="onBlur()" (blur)="onBlur()"
[placeholder]="'SEARCH.INPUT.PLACEHOLDER' | translate" [placeholder]="'SEARCH.INPUT.PLACEHOLDER' | translate"
autocomplete="off" autocomplete="off"
@@ -30,13 +30,11 @@ import { NO_ERRORS_SCHEMA } from '@angular/core';
describe('SearchInputControlComponent', () => { describe('SearchInputControlComponent', () => {
let fixture: ComponentFixture<SearchInputControlComponent>; let fixture: ComponentFixture<SearchInputControlComponent>;
let component: SearchInputControlComponent; let component: SearchInputControlComponent;
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
imports: [AppTestingModule, SearchInputControlComponent], imports: [AppTestingModule, SearchInputControlComponent],
schemas: [NO_ERRORS_SCHEMA] schemas: [NO_ERRORS_SCHEMA]
}); });
fixture = TestBed.createComponent(SearchInputControlComponent); fixture = TestBed.createComponent(SearchInputControlComponent);
component = fixture.componentInstance; component = fixture.componentInstance;
fixture.detectChanges(); fixture.detectChanges();
@@ -54,6 +52,7 @@ describe('SearchInputControlComponent', () => {
it('should not emit submit event if form is invalid', () => { it('should not emit submit event if form is invalid', () => {
component.searchTerm = ''; component.searchTerm = '';
spyOn(component.submit, 'emit'); spyOn(component.submit, 'emit');
component.searchSubmit(); component.searchSubmit();
expect(component.submit.emit).not.toHaveBeenCalled(); expect(component.submit.emit).not.toHaveBeenCalled();
@@ -63,14 +62,12 @@ describe('SearchInputControlComponent', () => {
let emittedSearchTerm = ''; let emittedSearchTerm = '';
component.searchChange.subscribe((searchTerm) => (emittedSearchTerm = searchTerm)); component.searchChange.subscribe((searchTerm) => (emittedSearchTerm = searchTerm));
component.searchTerm = 'mock-search-term'; component.searchTerm = 'mock-search-term';
expect(emittedSearchTerm).toBe('mock-search-term'); expect(emittedSearchTerm).toBe('mock-search-term');
}); });
it('should emit searchChange event on clear', () => { it('should emit searchChange event on clear', () => {
let emittedSearchTerm: string = null; let emittedSearchTerm: string = null;
component.searchChange.subscribe((searchTerm) => (emittedSearchTerm = searchTerm)); component.searchChange.subscribe((searchTerm) => (emittedSearchTerm = searchTerm));
component.clear(); component.clear();
expect(emittedSearchTerm).toBe(''); expect(emittedSearchTerm).toBe('');
}); });
@@ -78,18 +75,15 @@ describe('SearchInputControlComponent', () => {
it('should clear searchTerm', () => { it('should clear searchTerm', () => {
component.searchTerm = 'c'; component.searchTerm = 'c';
fixture.detectChanges(); fixture.detectChanges();
component.clear(); component.clear();
expect(component.searchTerm).toBe(''); expect(component.searchTerm).toBe('');
}); });
it('should check if searchTerm has a length less than 2', () => { it('should check if searchTerm has a length less than 2', () => {
expect(component.isTermTooShort()).toBe(false); expect(component.isTermTooShort()).toBe(false);
component.searchTerm = 'd'; component.searchTerm = 'd';
fixture.detectChanges(); fixture.detectChanges();
expect(component.isTermTooShort()).toBe(true); expect(component.isTermTooShort()).toBe(true);
component.searchTerm = 'dd'; component.searchTerm = 'dd';
fixture.detectChanges(); fixture.detectChanges();
expect(component.isTermTooShort()).toBe(false); expect(component.isTermTooShort()).toBe(false);
@@ -31,6 +31,7 @@ import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { FormControl, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; import { FormControl, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { noWhitespaceValidator } from 'projects/aca-content/folder-rules/src/rule-details/validators/no-whitespace.validator';
@Component({ @Component({
imports: [CommonModule, TranslatePipe, MatButtonModule, MatIconModule, MatFormFieldModule, MatInputModule, FormsModule, ReactiveFormsModule], imports: [CommonModule, TranslatePipe, MatButtonModule, MatIconModule, MatFormFieldModule, MatInputModule, FormsModule, ReactiveFormsModule],
@@ -65,7 +66,7 @@ export class SearchInputControlComponent implements OnInit {
@ViewChild('searchInput', { static: true }) @ViewChild('searchInput', { static: true })
searchInput: ElementRef; searchInput: ElementRef;
searchFieldFormControl = new FormControl('', [Validators.required]); searchFieldFormControl = new FormControl('', [Validators.required, noWhitespaceValidator()]);
get searchTerm(): string { get searchTerm(): string {
return this.searchFieldFormControl.value.replace('text:', 'TEXT:'); return this.searchFieldFormControl.value.replace('text:', 'TEXT:');
@@ -83,16 +84,14 @@ export class SearchInputControlComponent implements OnInit {
} }
openDropdown() { openDropdown() {
setTimeout(() => {
this.searchInput.nativeElement.focus(); this.searchInput.nativeElement.focus();
}, 0);
} }
searchSubmit() { searchSubmit() {
this.searchFieldFormControl.markAsTouched(); this.searchFieldFormControl.markAsTouched();
const trimmedTerm = this.searchTerm?.trim(); const trimmedTerm = this.searchTerm?.trim();
if (this.searchFieldFormControl.valid && trimmedTerm?.length > 0) { if (this.searchFieldFormControl.valid && trimmedTerm) {
this.submit.emit(trimmedTerm); this.submit.emit(trimmedTerm);
} }
} }
@@ -107,6 +106,6 @@ export class SearchInputControlComponent implements OnInit {
} }
isTermTooShort() { isTermTooShort() {
return !!(this.searchTerm && this.searchTerm.length < 2); return !!(this.searchTerm.trim() && this.searchTerm.trim().length < 2);
} }
} }
@@ -36,14 +36,16 @@
(submit)="onSearchSubmit($event)" (submit)="onSearchSubmit($event)"
(searchChange)="onSearchChange($event)" (searchChange)="onSearchChange($event)"
/> />
<div class="app-search-feedback"> <mat-error *ngIf="hasLibrariesConstraint" class="app-search-error">
<mat-hint *ngIf="hasLibrariesConstraint" class="app-search-hint">
{{ 'SEARCH.INPUT.HINT' | translate }} {{ 'SEARCH.INPUT.HINT' | translate }}
</mat-hint> </mat-error>
<mat-error *ngIf="searchInputControl.searchFieldFormControl.hasError('required') && searchInputControl.searchFieldFormControl.touched" class="app-search-error"> <mat-error
*ngIf="searchInputControl.searchFieldFormControl.errors?.required && searchInputControl.searchFieldFormControl.touched" class="app-search-error">
{{ 'SEARCH.INPUT.REQUIRED' | translate }} {{ 'SEARCH.INPUT.REQUIRED' | translate }}
</mat-error> </mat-error>
</div> <mat-error *ngIf="searchInputControl.searchFieldFormControl.errors?.whitespace && searchInputControl.searchFieldFormControl.touched" class="app-search-error">
{{ 'SEARCH.INPUT.WHITESPACE' | translate }}
</mat-error>
<div id="search-options" class="app-search-options"> <div id="search-options" class="app-search-options">
<mat-checkbox *ngFor="let option of searchOptions" <mat-checkbox *ngFor="let option of searchOptions"
@@ -55,7 +55,6 @@ $search-border-radius: 4px;
column-gap: 24px; column-gap: 24px;
} }
.app-search-hint,
.app-search-error { .app-search-error {
position: absolute; position: absolute;
gap: 4px; gap: 4px;
@@ -23,29 +23,62 @@
*/ */
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { UnitTestingUtils } from '@alfresco/adf-core';
import { MatError } from '@angular/material/form-field'; import { MatError } from '@angular/material/form-field';
import { AppStore } from '@alfresco/aca-shared/store'; import { AppStore } from '@alfresco/aca-shared/store';
import { By } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { AppTestingModule } from '../../../testing/app-testing.module'; import { AppTestingModule } from '../../../testing/app-testing.module';
import { SearchInputComponent } from './search-input.component'; import { SearchInputComponent } from './search-input.component';
import { SearchInputControlComponent } from '../search-input-control/search-input-control.component';
import { Store } from '@ngrx/store'; import { Store } from '@ngrx/store';
import { of } from 'rxjs'; import { of } from 'rxjs';
import { HarnessLoader } from '@angular/cdk/testing';
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
import { MatMenuHarness } from '@angular/material/menu/testing';
import { MatCheckboxHarness } from '@angular/material/checkbox/testing';
describe('SearchInputComponent', () => { describe('SearchInputComponent', () => {
let fixture: ComponentFixture<SearchInputComponent>; let fixture: ComponentFixture<SearchInputComponent>;
let component: SearchInputComponent; let component: SearchInputComponent;
let store: jasmine.SpyObj<Store<AppStore>>; let store: jasmine.SpyObj<Store<AppStore>>;
let unitTestingUtils: UnitTestingUtils;
let loader: HarnessLoader;
function getFirstError(): string {
const error = unitTestingUtils.getByDirective(MatError);
return error?.nativeElement.textContent.trim();
}
async function openMenu() {
const menu = await loader.getHarness(MatMenuHarness);
await menu.open();
return menu;
}
async function getCheckbox(id: string) {
const overlayLoader = TestbedHarnessEnvironment.documentRootLoader(fixture);
return overlayLoader.getHarness(MatCheckboxHarness.with({ selector: `#${id}` }));
}
async function uncheckAllCheckboxes() {
const checkboxIds = ['libraries', 'folder', 'content'];
for (const id of checkboxIds) {
try {
const checkbox = await getCheckbox(id);
if (await checkbox.isChecked()) {
await checkbox.uncheck();
fixture.detectChanges();
}
} catch (err) {
fail(`Checkbox with id ${id} not found`);
}
}
}
beforeEach(async () => { beforeEach(async () => {
const storeSpy = jasmine.createSpyObj<Store<AppStore>>('Store', ['dispatch', 'pipe']); const storeSpy = jasmine.createSpyObj<Store<AppStore>>('Store', ['dispatch', 'pipe']);
await TestBed.configureTestingModule({ await TestBed.configureTestingModule({
imports: [AppTestingModule, ReactiveFormsModule, SearchInputComponent, SearchInputControlComponent], imports: [AppTestingModule, SearchInputComponent],
providers: [{ provide: Store, useValue: storeSpy }], providers: [{ provide: Store, useValue: storeSpy }]
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents(); }).compileComponents();
fixture = TestBed.createComponent(SearchInputComponent); fixture = TestBed.createComponent(SearchInputComponent);
@@ -53,21 +86,13 @@ describe('SearchInputComponent', () => {
store = TestBed.inject(Store) as jasmine.SpyObj<Store<AppStore>>; store = TestBed.inject(Store) as jasmine.SpyObj<Store<AppStore>>;
store.pipe.and.returnValue(of([])); store.pipe.and.returnValue(of([]));
fixture.detectChanges(); fixture.detectChanges();
unitTestingUtils = new UnitTestingUtils(fixture.debugElement);
loader = TestbedHarnessEnvironment.loader(fixture);
}); });
function getFirstError(): string { it('should show required error when field is empty and touched', async () => {
const error = fixture.debugElement.query(By.directive(MatError)); await openMenu();
return error?.nativeElement.textContent.trim();
}
function openSearchContainer(): void {
const menuButton = fixture.debugElement.query(By.css('.app-search-container'));
menuButton?.nativeElement.click();
fixture.detectChanges();
}
it('should show required error when field is empty and touched', () => {
openSearchContainer();
component.searchInputControl.searchFieldFormControl.setValue(''); component.searchInputControl.searchFieldFormControl.setValue('');
component.searchInputControl.searchFieldFormControl.markAsTouched(); component.searchInputControl.searchFieldFormControl.markAsTouched();
fixture.detectChanges(); fixture.detectChanges();
@@ -75,47 +100,50 @@ describe('SearchInputComponent', () => {
expect(getFirstError()).toBe('SEARCH.INPUT.REQUIRED'); expect(getFirstError()).toBe('SEARCH.INPUT.REQUIRED');
}); });
it('should not show error when field has value', () => { it('should not show error when field has value', async () => {
openSearchContainer(); await openMenu();
component.searchInputControl.searchFieldFormControl.setValue('test');
component.searchInputControl.searchFieldFormControl.setValue('not giving up');
component.searchInputControl.searchFieldFormControl.markAsTouched(); component.searchInputControl.searchFieldFormControl.markAsTouched();
fixture.detectChanges(); fixture.detectChanges();
const error = fixture.debugElement.query(By.directive(MatError)); const error = unitTestingUtils.getByDirective(MatError);
expect(error).toBeNull(); expect(error).toBeNull();
}); });
it('should not show error when field is untouched', () => { it('should not show error when field is untouched', async () => {
openSearchContainer(); await openMenu();
component.searchInputControl.searchFieldFormControl.setValue(''); component.searchInputControl.searchFieldFormControl.setValue('');
component.searchInputControl.searchFieldFormControl.markAsUntouched(); component.searchInputControl.searchFieldFormControl.markAsUntouched();
fixture.detectChanges(); fixture.detectChanges();
const error = fixture.debugElement.query(By.directive(MatError)); const error = unitTestingUtils.getByDirective(MatError);
expect(error).toBeNull(); expect(error).toBeNull();
}); });
it('should dispatch SearchByTermAction when libraries are checked and term is new', () => { it('should dispatch action when Libraries checkbox selected and term is entered', async () => {
spyOn(component as any, 'isLibrariesChecked').and.returnValue(true); await openMenu();
spyOn(component as any, 'isFoldersChecked').and.returnValue(false); const checkbox = await getCheckbox('libraries');
spyOn(component as any, 'isFilesChecked').and.returnValue(false); await checkbox.check();
fixture.detectChanges();
component.searchedWord = 'test';
component.onSearchSubmit('Enter');
component.onSearchSubmit({ target: { value: 'happy faces only' } });
expect(store.dispatch).toHaveBeenCalled(); expect(store.dispatch).toHaveBeenCalled();
}); });
it('should not dispatch SearchByTermAction when no checkboxes are selected and term is empty', () => { it('should not dispatch SearchByTermAction when no checkboxes are selected and term is empty', async () => {
store.dispatch.calls.reset(); store.dispatch.calls.reset();
spyOn(component as any, 'isLibrariesChecked').and.returnValue(false); await openMenu();
spyOn(component as any, 'isFoldersChecked').and.returnValue(false); await uncheckAllCheckboxes();
spyOn(component as any, 'isFilesChecked').and.returnValue(false);
expect(component.searchOptions.every((option) => !option.value)).toBeTrue();
component.searchedWord = ''; component.searchedWord = '';
component.onSearchSubmit({ target: { value: '' } }); fixture.detectChanges();
component.onSearchSubmit({ target: { value: '' } });
expect(store.dispatch).not.toHaveBeenCalled(); expect(store.dispatch).not.toHaveBeenCalled();
}); });
}); });
@@ -73,6 +73,7 @@ export class SearchInputComponent implements OnInit, OnDestroy {
has400LibraryError = false; has400LibraryError = false;
hasLibrariesConstraint = false; hasLibrariesConstraint = false;
searchOnChange: boolean; searchOnChange: boolean;
isTrimmedWordEmpty = false;
searchedWord: string = null; searchedWord: string = null;
searchOptions: Array<SearchOptionModel> = [ searchOptions: Array<SearchOptionModel> = [
@@ -177,10 +178,15 @@ export class SearchInputComponent implements OnInit, OnDestroy {
*/ */
onSearchSubmit(event: any) { onSearchSubmit(event: any) {
const searchTerm = event.target ? (event.target as HTMLInputElement).value : event; const searchTerm = event.target ? (event.target as HTMLInputElement).value : event;
if (searchTerm) { const trimmedTerm = searchTerm.trim();
this.searchedWord = searchTerm;
if (trimmedTerm) {
this.searchedWord = trimmedTerm;
if (this.isLibrariesChecked() && this.searchInputControl.isTermTooShort()) {
return;
} else {
this.searchByOption(); this.searchByOption();
}
} else { } else {
this.notificationService.showError('APP.BROWSE.SEARCH.EMPTY_SEARCH'); this.notificationService.showError('APP.BROWSE.SEARCH.EMPTY_SEARCH');
} }