I'm currently facing an issue with unit testing a functionality that works perfectly on the front-end but the unit test is not working as expected. Below you can find my current unit test, which is still in progress as I am focusing on getting the basic test to function before moving on to more complex checks.
@Component({
template : '<input appInputFilter filterType="alphanumericOnly" type="text" minlength="2">'
})
class TestComponent {
}
describe('InputFilterDirective', () => {
let comp: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let de: DebugElement;
// const el: HTMLElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations : [InputFilterDirective, TestComponent]
});
fixture = TestBed.createComponent(TestComponent);
comp = fixture.componentInstance;
de = fixture.debugElement.query(By.directive(InputFilterDirective));
});
it('should create instance of inputFilter', () => {
expect(comp).toBeTruthy();
expect(de).toBeDefined();
});
it('should only allow onlyNumbers', async(() => {
fixture.detectChanges();
const keyEvent = new KeyboardEvent('keydown', {'code': 'KeyQ'});
const input = de.nativeElement as HTMLInputElement;
input.dispatchEvent(keyEvent);
expect(input.value).toEqual('q');
expect(true).toBeTruthy();
}));
});
Here is the full directive code:
import { Directive, ElementRef, HostListener, Input } from '@angular/core';
@Directive({
selector: '[appInputFilter]',
})
export class InputFilterDirective {
private el : any;
private specialKeys : Array<string> = ['Backspace', 'Tab', 'End', 'Home'];
@Input() public filterType : any;
constructor(el: ElementRef) {
this.el = el;
}
@HostListener('keydown', ['$event'])
onKeyDown(event: KeyboardEvent) {
if (this.specialKeys.indexOf(event.key) !== -1) {
return;
}
switch (this.filterType) {
case 'onlyNumber':
this.appFilter(event, new RegExp(/\D/g));
break;
case 'alphanumericOnly':
this.appFilter(event, new RegExp(/\W/g));
break;
case 'alphabeticAndSpecial':
this.appFilter(event, new RegExp(/[^a-zA-Z'-]/));
break;
case 'ipAddress':
this.appFilter(event, new RegExp(/[^0-9.]/g));
break;
}
};
appFilter(event: KeyboardEvent, regex: RegExp) {
const current: string = this.el.nativeElement.value;
const next: string = current.concat(event.key);
if (next && String(next).match(regex)) {
event.preventDefault();
}
};
}
Additional information:
- I've tried various KeyEvents such as typing '1' without success.
- The unit test has been run both asynchronously and synchronously.
- I have followed tips from Stack Overflow regarding how others have tested HostListeners, but unfortunately, it's not working for me and I'm unsure why.
Any help would be greatly appreciated. As mentioned, this is just a basic test where I'm using the filter to specifically target alphanumeric characters (as seen in the directive code).
If the issue lies with detecting changes, I'm open to listening for "preventDefault" to make the test work. Feel free to suggest any adjustments needed.