Reputation: 1630
I have a directive that I am trying to test. But the length of the value in the directive is always undefined.
What am I doing wrong?
@Directive({
selector: '[evAutoTab]'
})
export class EvAutoTabDirective {
@Input('evAutoTab') destId: string;
@HostListener('keyup') onKeyup() {
this.moveFocus();
}
constructor(private el: ElementRef) {
}
private moveFocus() {
const maxLen = this.el.nativeElement.getAttribute('maxlength');
const len = this.el.nativeElement.valueOf().length;
console.log(`len ${len} maxLen ${maxLen}`);
if (len === maxLen) {
const next: HTMLElement = document.querySelector('#' + this.destId);
next.focus();
}
}
}
The test component:
@Component({
template: `
<div>
<input evAutoTab="'AutoTab1'" id="AutoTab0" maxlength="4" value=""/>
<input evAutoTab id="AutoTab1" value=""/>
<input evAutoTab id="AutoTab2" value=""/>
</div>
<div>
<input evAutoTab id="AutoTab3" value=""/>
<input evAutoTab id="AutoTab4" value=""/>
<input evAutoTab id="AutoTab5" value=""/>
</div>
`
})
class TestComponent {
constructor() {
}
}
And the test
it('should move focus from first element if maxlength is reached', async () => {
const debugEl: HTMLElement = fixture.debugElement.nativeElement;
const autoTab0: HTMLInputElement = debugEl.querySelector('#AutoTab0');
// verify setup
autoTab0.focus();
expect(document.activeElement.id).toBe('AutoTab0');
// act
autoTab0.value = '1999';
autoTab0.dispatchEvent(new Event('keyup'));
fixture.detectChanges();
expect(document.activeElement.id).toBe('AutoTab1');
});
I have tried trigger n input event before the key also, but the valueof statement always returns undefined
Upvotes: 0
Views: 134
Reputation: 18859
Can you try the uncommented line instead of the commented one in your directive? Does the directive work when code is served but not in unit test? It is the first time I am seeing valueOf()
.
// const len = this.el.nativeElement.valueOf().length;
const len = this.el.nativeElement.value.length;
Upvotes: 1