I have a directive numbersOnly which applied to input type textbox. Here is my Component HTML
<input type="text" class="form-control" id="productIndex"
required
numbersOnly
name="productId"
placeholder="Enter Product Index"
#postProduct
(keyup)="onProductAdd(postProduct)"
/>
A very simple directive which restricts from entering any alphabet
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[numbersOnly]'
})
export class NumbersOnlyDirective {
constructor(private _el: ElementRef) { }
@HostListener('input', ['$event']) onInputChange(event) {
const initalValue = this._el.nativeElement.value;
this._el.nativeElement.value = initalValue.replace(/[^0-9]*/g, '');
if (initalValue !== this._el.nativeElement.value) {
event.preventDefault();
}
}
}
Now, when writing the Unit test case using jasmine, it is always showing me an error. Below is my UT file. (Note: Keydown event is getting fired)
import {ComponentFixture, TestBed} from '@angular/core/testing';
import { NumbersOnlyDirective } from './numbers-only.directive';
import { Component, DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { By } from '@angular/platform-browser';
@Component({
template: `<input numbersOnly type="text" name="productId" />`
})
// tslint:disable-next-line:no-unnecessary-class
class TestAllowOnlyNumbersComponent {
// allowNumbers = true;
}
fdescribe('Directive: numbersOnly', () => {
let component: TestAllowOnlyNumbersComponent;
let fixture: ComponentFixture<TestAllowOnlyNumbersComponent>;
let inputEl: DebugElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestAllowOnlyNumbersComponent, NumbersOnlyDirective],
schemas: [ NO_ERRORS_SCHEMA ],
});
fixture = TestBed.createComponent(TestAllowOnlyNumbersComponent);
component = fixture.componentInstance;
inputEl = fixture.debugElement.query(By.css('input[name="productId"]'));
fixture.detectChanges();
});
it('keydown input', () => {
const event = new KeyboardEvent('keydown', { key: 'F' });
inputEl.nativeElement.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
});
});