我有一个我正在尝试测试的指令。但是指令中的值的长度始终是未定义的。
我做错了什么?
@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();
}
}
}测试组件:
@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() {
}
}和测试
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');
});我也尝试过在键之前触发n个输入事件,但valueof语句总是返回undefined
发布于 2020-03-17 22:09:00
你能在你的指令中尝试未注释的行而不是注释的行吗?在提供代码但不在单元测试中时,该指令是否起作用?这是我第一次见到valueOf()。
// const len = this.el.nativeElement.valueOf().length;
const len = this.el.nativeElement.value.length;https://stackoverflow.com/questions/60715290
复制相似问题