I made a custom directive for text masking in my ionic application. The directive is for input text masking for the phone number.
It uses ngControl
to get and set the values of the input field.
@HostListener('keyup', ['$event'])
onKeyUp($event: any) {
var inputValue = this.ngControl.control.value;
this.ngControl.control.setValue(this.getMaskedValue(inputValue));
}
}
I tried many approaches to test it but I was unable to set the value. I was able to get ngControl
by importing the FormsModule
and binding the input.
But I still can't get value as this.ngControl.control.value
. When I type in the input field, it works fine but unable to define test case.
here is the test case snippet
it('should have masked value', () => {
fixture.detectChanges();
let element = inputEl.nativeElement;
element.value = '999';
inputEl.nativeElement.dispatchEvent(new Event('keyup', key));
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(element.value).toEqual('(999)');
});
}
This is my test component :
@Component({
template: `<input type="text" [(ngModel)]="val" customDirective="(999)-999-9999">`
})
class TestCustomDirectiveComponent {
constructor(public formBuilder: FormBuilder) {}
val = '';
}
I want to write a test case like this expect(element.value).toEqual('(999)-999-9999
. How can I test it?